/**
 * Created by Administrator on 2017/3/25.
 */
angular.module('HTRD_AutoConsole.A').directive('bbb',[function() {
	var $scope, $node;

	var link = function(s, e) {
    var page = 1;
    var pageList = [];

    var activePage = function(item) {
      console.log(item);
      // $emit('');
    };

		var parseDOM = function() {
			$scope = s;
			$node = $(e[0]);
		};

		var bindListener = function() {
      $scope.activePage = activePage;
		};

		var initPlugins = function() {
      console.log('initPlugins');
      $scope.$emit('toparents',{name:'child-parents'});
      $scope.$on('tolist',function(evt,data){
        $scope.page = Math.ceil(data.total / data.pageSize);

        for (var i = 0;i < $scope.page;i++) {

          var model = {
            index: (i + 1)
          };

          if (data.pageNo === (i + 1)) {
            model.active = true;
          };

          pageList.push(model);
        };

        $scope.pageList = pageList;

        console.log($scope.pageList);
      })
		};

		parseDOM();
		bindListener();
		initPlugins();
	};

	return {
		'replace': true,
		'restrict' : 'AEC',
		'scope': {},
		'link': link,
		'templateUrl': 'view/directive/util/bbb.html'
	};
}]);

angular.module('HTRD_AutoConsole.A').directive('breadcrumbs', [function() {
  var $scope, $node;
  var link = function(s, e) {

    var parseDom = function() {
      $scope = s;
      $node = $(e[0]);
    };

    var bindListener = function() {
      
    };

    var initPlugins = function() {
      console.log($scope.data);
    };

    parseDom();
    bindListener();
    initPlugins();
  };

  return {
    'restrict': 'AE',
    'replace': true,
    'templateUrl': 'view/directive/util/breadcrumbs.html',
    'scope': {
      'data': '='
    },
    'link': link,
  };
}]);
// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('category',[function() {
  var link = function(s, e) {
      var $scope, $node;

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };
   
      var bindListener = function() {

      };

      var initPlugins = function() {

      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'list': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/category.html'
  };
}]);

// 面包屑
angular.module('HTRD_AutoConsole.A').directive('crumbs',['$state', function($state) {
  var link = function(s, e) {
    var $scope, $node;

    var activeIndex = function(item) {
      console.log('item', item);

      if (!!item.url) {
        $state.go(item.url);
      };
    };

    var parseDOM = function() {
      $scope = s;
      $node = $(e[0]);
    };

    var bindListener = function() {
      $scope.activeIndex = activeIndex;
    };

    var initPlugins = function() {

      // $scope.config = {
      //   index: {
      //     title: '运维管理',
      //     url: 'console.base.home.index',
      //     icon: 'htrd-c-icon crumbs home'
      //   },
      //
      //   items: [
      //     {
      //       title: '流程列表',
      //       icon: 'htrd-c-icon crumbs right',
      //       url: ''
      //     },
      //
      //     {
      //       title: '流程详情',
      //       icon: 'htrd-c-icon crumbs right'
      //     }
      //   ]
      // }
    };

    var init = function() {
      parseDOM();
      bindListener();
      initPlugins();
    };

    init();
  };
  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'config': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/crumbs.html'
  };
}]);

// 时间
// angular.module('HTRD_AutoConsole.A').directive('datepicker',[function() {
//   var $scope, $node;
//   var link = function(s, e) {
//       var parseDOM = function() {
//         $scope = s;
//         $node = $(e[0]);
//       };

//       var bindListener = function() {

//       };

//       var initPlugins = function() {

//       };

//       var init = function() {
//         parseDOM();
//         bindListener();
//         initPlugins();
//       };

//       init();
//   };
//   return {
//       'replace': true,
//       'restrict' : 'AEC',
//       'scope': {},
//       'link': link,
//       'templateUrl': 'view/directive/util/datepicker.html'
//   };
// }]);

// 时间
angular.module('HTRD_AutoConsole.A').directive('dateTimePicker',[function() {
  var $scope, $node;
  var link = function(s, e) {

     /*var changeData = function(){
        if ((!!$scope.startDate && !!!$scope.endDate) || (!!!$scope.endDate && !!$scope.startDate)) {
          $scope.$emit("showBtn",{
            isClick : true;
          })
        } else{
          $scope.$emit("showBtn",{
             isClick : false;
          })
        }
      }*/
       /*当前时间格式*/
       var date = new Date();
        var endDate = function (){
                    Y = date.getFullYear() + '-';
                    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
                    D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
                    h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
                    m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes());
            return Y+M+D+h+m;
        };

        /*倒退一月时间格式*/
        var startDate = function(){
          var time = Date.parse(date) - 30*24*60*60*1000;
                nowTime = new Date(time);
                    Y = nowTime.getFullYear() + '-';
                    M = (nowTime.getMonth() +1< 10 ? '0'+(nowTime.getMonth()+1) : nowTime.getMonth()+1) + '-';
                    D = (nowTime.getDate() < 10 ? '0'+(nowTime.getDate()) : nowTime.getDate()) + ' ';
                    h = (nowTime.getHours() < 10 ? '0'+(nowTime.getHours()) : nowTime.getHours()) + ':';
                    m =(nowTime.getMinutes() < 10 ? '0'+(nowTime.getMinutes()) : nowTime.getMinutes());
            return Y+M+D+h+m;
        };

        /*时间格式转时间戳*/
        var getTime = function(dateStr){
          var newstr = dateStr.replace(/-/g,'/'); 
          var date =  new Date(newstr); 
          var time_str = date.getTime();
          return time_str;
        };

      /*时间戳比较,改变查询的状态*/
      var changeData = function(e){
        console.log(e)

        /*时间戳格式*/
        var startTime = getTime($scope.min_date);
        var endTime = getTime($scope.max_date);
        if(startTime>endTime){
          $scope.$emit("showBtn",{
            isClick : true,
            min_date:$scope.min_date,
            max_date:$scope.max_date
          })
        }else{
          $scope.$emit("showBtn",{
            isClick : false,
            min_date:$scope.min_date,
            max_date:$scope.max_date
          })
        }
      }

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.changeData =changeData;
      };

      var initPlugins = function() {
        $scope.max_date= endDate();
        $scope.min_date = startDate(); 

        $scope.$emit('toDate',{
        min_date: $scope.min_date,
        max_date: $scope.max_date
      });

    	   $node.find('input').datetimepicker({
            weekStart: 1,
            todayBtn:  1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 0,
            showMeridian: 1
        });
      };


      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };
  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {},
      'link': link,
      'templateUrl': 'view/directive/util/dateTimePicker.html'
  };
}]);

// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('dropdownmenu',[function() {
  var link = function(s, e) {
    var $scope, $node;
    var activeMenu = function(item) {
      //console.log(item+'drop');
      $scope.defaultText = item.title || item.name || item;
      $scope.defaultId = item.id || 0;
      $scope.callBack && $scope.callBack(item);
    };

    var parseDOM = function() {
      $scope = s;
      $node = $(e[0]);
    };

    var bindListener = function() {
      $scope.activeMenu = activeMenu;
    };

    var initPlugins = function() {
      $scope.defaultText = $scope.defaultText || '请选择';
    };

    parseDOM();
    bindListener();
    initPlugins();
  };

  return {
    'replace': true,
    'restrict' : 'AEC',
    'scope': {
      'list': '=',
      'callBack': '=',
      'defaultText': '=',
      'defaultId': '='
    },
    'link': link,
    'templateUrl': 'view/directive/util/dropdownMenu.html'
  };
}]);

angular.module('HTRD_AutoConsole.A').directive('homeList',['$state','StatusMapServ',
function($state,StatusMapServ) {
  var link = function(s, e) {
    var $scope, $node;
    var title;

    var statusMap = {
      1:{
        text:"检测异常"
      },
      2:{
        text:"执行超时"
      },
      3:{
        text:"执行错误"
      }
    };

    var tag = [
       {
         text: "今日待执行",
         url:'console.base.home.waitlist'
       },
      {
         text:"今日执行中",
         url:'console.base.home.runlist'
       },
       {
         text:"今日执行告警",
         url:'console.base.home.warnlist'
       },
       {
         text:"今日已结束",
         url:'console.base.home.endlist'
       },
       {
         text:"今日执行成功",
         url:'console.base.home.successlist'
       },
       {
         text:"今日手工接管",
         url:'console.base.home.handlist'
       }
   ];

   //查看流程的list
   var getLook = function (item) {

     if($scope.index === "0" || $scope.index === "1" || $scope.index === "2"){
       $state.go('console.base.manager.process',{id:item.pipeline});
     }else{
      console.log(item.id+'---'+item.pipeline)
       $state.go('console.base.manager.historyProcess',{
         id: item.id,
         processId: item.pipeline
       });
     }
   };

   var getMoreList = function(index){
      $state.go(tag[index].url)
   };

    var parseDom = function() {
      $scope = s;
      $node = $(e[0]);
    };

    var bindListener = function() {
      $scope.getLook = getLook;
      $scope.getMoreList = getMoreList
    };

    var initPlugins = function() {

      title = tag[$scope.index].text;

      $scope.title = title;

      //今日待执行的显示;
      switch($scope.index)
        {
           case '1':
           case '3':
            $scope.data.data.map(function(item){
              var model = StatusMapServ.getStatusData(item.result_status);
              item.result_status = model.text.substring(0,4);
           });
           break;

          case '2':
             $scope.data.data.map(function(item){
                item.pipeline_name = item.result_info;
             });
            break;

           case '4':
            $scope.data.data.map(function(item){
              var model = StatusMapServ.getStatusData(item.result_status);
              item.result_status =' ';
           });
           break;


           case '5':
            $scope.data.data.map(function(item){
              var model = StatusMapServ.getStatusData(item.result_status);
              item.result_status = model.text.replace('手工接管'||'手工接管后的执行结果：', '');
              if(item.result_status.indexOf('手工接管后的执行结果：')){
                item.result_status = model.text.replace('手工接管后的执行结果：', '');
              }else if(item.result_status.indexOf('手工接管')){
                item.result_status = model.text.replace('手工接管', '');
              }
           });
           break;
        };

  };

    var init = function() {
      parseDom();
      bindListener();
      initPlugins();
    };

    init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'data': '=',
        'index': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/homeList.html'
  };
}]);

// 选项卡
angular.module('HTRD_AutoConsole.A').directive('htrdtable',[function() {
  var $scope, $node;
  var link = function(s, e) {

    var parseDOM = function() {
      $scope = s;
      $node = $(e[0]);
    };

    var bindListener = function() {

    };

    var initPlugins = function() {

      $scope.$watch("data",function () {

      })
    };

    var init = function() {
      parseDOM();
      bindListener();
      initPlugins();
    };

    init();
  };
  return {
    'replace': true,
    'restrict' : 'AEC',
    'scope': {
      'data': '='
    },
    'link': link,
    'templateUrl': 'view/directive/util/htrdTable.html'
  };
}]);


/**
 * Created by Administrator on 2017/3/24.
 */
angular.module('HTRD_AutoConsole.A').directive('log1',function () {
	var $scope, $node;
	var link = function () {

		var parseDOM = function() {
			$scope = s;
			$node = $(e[0]);
		};

		var bindListener = function() {

		};

		var initPlugins = function() {

			// 打印传递进来的数据
			console.log($scope.logInfo1);
		};

		parseDOM();
		bindListener();
		initPlugins();
	};
	return {
		'replace': true,
		'restrict' : 'AEC',
		'scope': {
			// 传递进来的数据
			'logInfo1': '='
		},
		'link': link,
		'templateUrl': 'view/directive/util/log1.html'
	}
})
// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('menu',[function() {
  var link = function(s, e) {
      var $scope, $node;

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {

      };

      var initPlugins = function() {

      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'list': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/menu.html'
  };
}]);

// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('message',['MessagePanelServ','DialogServ','AlertServ','$state',function(MessagePanelServ,DialogServ,AlertServ,$state) {
  var link = function(s, e) {
      var $scope, $node, strapModal;

      //清空消息;弹出框
      var clearMessage = function () {
        strapModal = DialogServ.modal({
          'scope': $scope,
          'templateUrl': 'view/console/modal/testModal.html'
        });
        strapModal.$promise.then(strapModal.show);
      };

      //弹出框的确定按钮
      var clearMessageSure = function () {
        strapModal.hide();
        $scope.$emit("clearMsg",{
          messagePanelState: false,
          messageCount: 0,
          messageData: []
        });
      };

      //点击查看
      var messageLook = function (item) {

        MessagePanelServ.getManagerOperation(item)
          .then(function(resuit){

            if(resuit.status === 200){

              if($scope.count > 99){
                    $scope.count -= 1;
                    $scope.messageData.splice(item.$index, 1);
                }else{
                    $scope.messageData.splice(item.$index, 1);
                    $scope.messageCount -= 1;
                };

                 $scope.$emit("countReduce",{
                  messageCount: $scope.messageCount,
                });

                //根据返回的is_exec 确定跳转的流程/执行id
                if (!item.is_exec) {

                  $state.go("console.base.manager.process",{id: item.pipeline_id});

                } else {

                  $state.go("console.base.manager.historyProcess",{id: item.ex_pl_id, processId: item.pipeline_id});

                }
            };
          })
      };

      //点击忽略
      var messageIgnore = function (item) {

        event.stopPropagation();

        MessagePanelServ.getManagerOperation(item)
          .then(function(resuit){

            if(resuit.status === 200){

              AlertServ.showSuccess('忽略成功');

              if($scope.count > 99){
                  $scope.count -= 1;
                  $scope.messageData.splice(item.$index, 1);
                }else{
                  $scope.messageData.splice(item.$index, 1);
                   $scope.messageCount -= 1;
                };

                $scope.$emit("countReduce",{
                  messageCount: $scope.messageCount,
                  messagePanelState: true,
                });

            }else{
              AlertServ.showSuccess('忽略失败');
            };
          })
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.clearMessage = clearMessage;
        $scope.clearMessageSure =clearMessageSure;
        $scope.messageLook =messageLook;
        $scope.messageIgnore = messageIgnore
      };

      var initPlugins = function() {
        $scope.$on("messageCount",function (evt,data) {
          $scope.messageCount = data.messageCount;
          $scope.count = data.count;
        });
        //console.log("消息中心"+$scope.messageData)
      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        "messageData": '=',
        "messageCount": '='
      },
      'link': link,
      'templateUrl': 'view/directive/message/messagePanel.html'
  };
}]);

// 迷你图表
angular.module('HTRD_AutoConsole.A').directive('miniChart',[function() {
  var link = function(s, e) {

      var $scope, $node;

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {

      };

      var initPlugins = function() {
        $scope.$watch('data', function() {

          if (!!$scope.data) {
            var chartNode = $node.find('.mainChart')[0];

            // 基于准备好的dom，初始化echarts图表
            var chart = echarts.init(chartNode);

            var option = {
                grid: {
                  x: 30,
                  y: 20,
                  x2: 10,
                  y2: 20
                },
                tooltip: {
                    show: true
                },
                legend: {
                    data: $scope.data.title
                },
                xAxis : [
                    {
                        type : 'category',
                        data : $scope.data.xAxis
                    }
                ],
                yAxis : [
                    {
                        type : 'value'
                    }
                ],
                series : [
                    {
                        "name": $scope.data.title[0],
                        "type": "line",
                        "data": $scope.data.series
                    }
                ]
            };

            chart.setOption(option);
          };
        });
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };
  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'data': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/miniChart.html'
  };
}]);

// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('multipleSelect',[function() {
  var link = function(s, e) {
      var $scope, $node;

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {

      };

      var initPlugins = function() {
        $node.find("select").multipleSelect({
          filter: true
        });

      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'list': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/multipleSelect.html'
  };
}]);

// 拓扑图编辑
angular.module('HTRD_AutoConsole.A').directive('multiSelect',['$window', '$timeout',  function($window, $timeout) {
  var link = function(s, e) {
      var $scope, $node, allList, queryList;

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {

      };


      var initPlugins = function() {
        allList = $scope.allData && $scope.allData.map(function(item, index) {
          item.value = item.name;
          delete item.name;
          return item;
        });

        queryList = $scope.queryData && $scope.queryData.map(function(item,index){
          item.value = item.name;
          delete item.name;
          return item;
        });

        allList && allList.map(function(allItem, allIndex) {
          queryList && queryList.map(function(item, index) {

            if (allItem.id === item.id) {
              allItem.select = true;
            };
          });
        });



        $node.find('#pre-selected-options').multiSelect({
          selectableHeader: "<input type='text' class='search-input form-contro' autocomplete='off' placeholder='请输入名称'>",
          selectionHeader: "<input type='text' class='search-input form-contro' autocomplete='off' placeholder='请输入名称'>",
          selectableFooter: "<div id='select-all'>全选</div>",
          selectionFooter: "<div id='deselect-all'>全不选</div>",
          // optionList: $scope.data,
          optionList: allList,
          afterInit: function(ms){
            var that = this,
            $selectableSearch = that.$selectableUl.prev(),
            $selectionSearch = that.$selectionUl.prev(),
            selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',
            selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected';

            that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
              .on('keydown', function(e){
                if (e.which === 40){
                  that.$selectableUl.focus();
                  return false;
                }
            });


            that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
              .on('keydown', function(e){
                if (e.which == 40){
                  that.$selectionUl.focus();
                  return false;
                }
              });
          },

          afterSelect: function (values){
            //console.log('left -> right values', values);

            if(Array.isArray(values)){

              if(values.length > 1){
                queryList = values;
              }else{
                queryList.push(values[0])
              }
              //console.log('queryList',queryList)
              $scope.$emit('selectValue',{
                selectData:queryList,
                tag: $scope.tag
              });
            }
          },

          afterDeselect: function(values){
            //console.log('right -> left values', values);
            if(Array.isArray(values)){

              if(values.length > 1){
                queryList = [];
              }else{
                var index = queryList.indexOf(values[0])
                queryList.splice(index,1)
              }
             //console.log('queryList',queryList)
            };

            $scope.$emit('selectValue',{
              selectData:queryList,
              tag: $scope.tag
            })
          }
        });

        $node.find('#select-all').click(function(){
          $node.find('#pre-selected-options').multiSelect('select_all');
              return false;
        });
        $node.find('#deselect-all').click(function(){
          $node.find('#pre-selected-options').multiSelect('deselect_all');
              return false;
        });
      };
      parseDOM();
      bindListener();
      initPlugins();
  };


  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'title': '=',
        'allData': '=',
        'queryData': '=',
        'tag': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/multiSelect.html'
  };
}]);

// 分页
angular.module('HTRD_AutoConsole.A').directive('page',[function() {
	var link = function(s, e) {
		var $scope, $node;

		var toTopPage = function() {
			$scope.toIndexPage(1);
		};

		var toLastPage = function() {
			$scope.toIndexPage($scope.pageConfig.pageCount);
		};

		var toNextPage = function() {
			$scope.toIndexPage($scope.pageConfig.pageNo + 1);
		};

		var toPrevPage = function() {
			$scope.toIndexPage($scope.pageConfig.pageNo - 1);
		};

		var queryPage = function() {

			if (!typeof $scope.queryPageValue === 'number') {
				return false;
			}
			else if ($scope.queryPageValue >= 1 && $scope.queryPageValue <= $scope.pageConfig.pageCount) {
				$scope.toIndexPage($scope.queryPageValue);
			};
		};

		var toIndexPage = function(index, isInit) {

			if (index < 1) {
				index = 1;
			}
			else if (index > $scope.pageConfig.pageCount) {
				index = $scope.pageConfig.pageCount;
			};

			$scope.pageConfig.pageList.map(function(item) {

				if (item.index === index) {
					item.active = true;
				} else {
					item.active = false;
				};
			});

			// 判断是否是在首页 / 尾页
			$scope.pageConfig.isTop = ($scope.pageConfig.pageNo == 1);
			$scope.pageConfig.isLast = ($scope.pageConfig.pageNo == $scope.pageConfig.pageCount);


			if (!!!isInit) {
				$scope.$emit('toPage', {
					page: index
				});
			};
		};

		var createPageList = function(start, end, isPrev) {
			var pageListSize = 0;
			var pageList = [];

			if (isPrev) {

				// 如果总页数 小于5页
				if ($scope.pageConfig.pageCount < end) {
					end = $scope.pageConfig.pageCount;
				}
			};

			pageListSize = end - start;

			for (var i = start;i < end;i++) {
				pageList.push({
					index: (i + 1)
				});
			};

			$scope.pageConfig.pageList = pageList;
		};

		var parseDOM = function() {
			$scope = s;
			$node = $(e[0]);
		};

		var bindListener = function() {
			$scope.toTopPage = toTopPage;
			$scope.toLastPage = toLastPage;
			$scope.toNextPage = toNextPage;
			$scope.toPrevPage = toPrevPage;
			$scope.toIndexPage = toIndexPage;
			$scope.createPageList = createPageList;
			$scope.queryPage = queryPage;
		};

		var initPlugins = function() {
			$scope.pageConfig = {};

			// 接收数据传入
			$scope.$on('toList', function (evt, data) {
				data.limit = data.limit || 20;

				// 保存分页基本配置
				// pageNo 当前第几页
				// pageSize 每页大小 默认20
				// pageCount 共多少页
				// totalCount 共多少条
				$scope.pageConfig = {
					pageNo: data.page,
					pageList: data.list,
					pageSize: data.limit || 20,
					pageCount: Math.ceil(data.count / data.limit),
					totalCount: data.count
				};

				$scope.queryPageValue = $scope.pageConfig.pageNo;

				// 判断当前pageNo
				// 显示不同的index 数量

				// 总页数大于1
				if ($scope.pageConfig.pageCount > 1) {

					// 当前页数 小于5
					if ($scope.pageConfig.pageNo <= 4) {
						createPageList(0, 5, true);
						$scope.toIndexPage($scope.pageConfig.pageNo, true);
					}

					else if ($scope.pageConfig.pageNo > 4 && $scope.pageConfig.pageNo < 6) {
						createPageList(0, $scope.pageConfig.pageNo + 1, true);
						$scope.toIndexPage($scope.pageConfig.pageNo, true);
					}

					else if ($scope.pageConfig.pageNo == 6) {
						createPageList($scope.pageConfig.pageNo - 4, $scope.pageConfig.pageNo + 2, true);
						$scope.toIndexPage($scope.pageConfig.pageNo, true);
					}

					else if ($scope.pageConfig.pageNo > 6) {
						createPageList($scope.pageConfig.pageNo - 5, $scope.pageConfig.pageNo + 1, true);
						$scope.toIndexPage($scope.pageConfig.pageNo, true);
					};
				}
			});

		};

		var init = function() {
			parseDOM();
			bindListener();
			initPlugins();
		};

		init();
	};
	return {
		'replace': true,
		'restrict' : 'AEC',
		'scope': {
			'data': '='
		},
		'link': link,
		'templateUrl': 'view/directive/util/page.html'
	};
}]);

// 拓扑图预览
angular.module('HTRD_AutoConsole.A').directive('quneeEditer',['$window', '$timeout', '$interval', '$stateParams', '$rootScope', 'ManagerProcessQuneeServ', 'DialogServ', 'SocketServ', 'AlertServ', 'ParseMapServ', 'DateParseServ',
function($window, $timeout, $interval, $stateParams, $rootScope, ManagerProcessQuneeServ, DialogServ, SocketServ, AlertServ, ParseMapServ, DateParseServ) {
  var link = function(s, e) {
      var $scope, $node, testCount = 0;
      var quneeStart, strapModal;

      // 流程id
      var processId = 0;

      // 执行id
      var execId;

      var nodeStatusMap = {
        // -1: 'st_unknow',  未知状态

        // 流程初始化
        0: 'init'
        ,
        // # 正在检测
        1: 'check',

        // # 流程检测错误
        2: 'checkError',

        // # 节点检测－脚本错误
        3: 'checkScriptError',

        // # 节点检测－主机错误
        4: 'checkError',

        // # 检测成功
        5: 'checkSuccess',

        // # 正在执行
        6: 'running',

        // # 执行错误
        7: 'runError',

        // # 执行超时
        8: 'runTimeout',

        // # 执行成功
        9: 'runSuccess',

        // # 等待用户确认
        10: 'waitUserConfirm',

        // # 停止执行
        11: 'quit',

        // # 正在停止
        12: 'st_stopping',

        // # 暂停执行
        13: 'pause',

        // # 正在暂停
        14: 'st_pausing',

        // # 等待用户输入
        15: 'st_waiting_for_input',

        // # 执行单个节点/重做
        16: 'st_running_one',

        // # 执行单个节点/重做 成功
        17: 'st_run_one_ok',

        // # 执行单个节点/重做 失败
        18: 'st_run_one_err',

        // # 用户拒绝
        19: 'st_confirm_refused',

        // 执行完成但有错误
        20: 'runSuccessAndNodeError',

        // 手工接管后的执行结果：成功
        21: 'takeOverSucc',

        // 手工接管后的执行结果：失败
        22: 'takeOverError'
      };

      // 如果状态为数字 则转换
      var quneeStateMap = {
        0: 'init', // 默认(1级分类)
        1: 'check', // 检测中(1级分类)
        2: 'exec', // 执行中(1级分类)
        3: 'checkError', // 检测异常(2级分类)
        4: 'checkSuccess', // 检测成功(2级分类)
        5: 'execSuccess' // 执行成功
      };

      // 执行中状态
      var runningMap = {
        0: 'pause',
        1: 'running'
      };

      // 执行中节点状态
      var runningNodeMap = {
        0: 'error',
        1: 'overtime',
        2: 'runningSuccess'
      };

      // var quneeRefTypeMap = {
      //   0: 'basicNode',
      //   1: 'logicNode',
      //   2: 'userConfirmNode',
      //   3: 'userInputNode',
      //   4: 'groupNode',
      //   5: 'startNode',
      //   6: 'endNode',
      //   7: 'closeNode',
      //   8: 'restartNode'
      // };

      var quneeRefTypeMap = {
        1: 'basicNode',
        2: 'userConfirmNode',
        3: 'groupNode',
        4: 'startNode',
        5: 'endNode',
        6: 'closeNode',
        7: 'restartNode'
      };

      // 流程执行结果字典
      var quneeExecStatus = {
        6: '执行中',
        7: '执行错误',
        8: '执行超时',
        9: '执行成功',
        10: '等待确认',
        11: '手工终止',
        12: '正在停止',
        13: '已暂停',
        14: '正在暂停',
        19: '用户不认可终止',
        20: '执行完成但有错误',
        21: '手工接管后的执行结果：成功',
        22: '手工接管后的执行结果：失败'
      };

      var resetNodes = function() {
        var refId;
        $scope.nodeList = quneeParseNodeJSON($scope.pipeline);

        // 先获取全部node
        selfJson = JSON.parse($scope.getChartJSON());
        selfJson.datas.map(function(selfItem, index) {

          // 更新普通节点
          if (selfItem._className === 'Q.Node') {

            if (!!!selfItem.json.properties.data.id) {
              refId = selfItem.json.properties.data.$ref;
              selfItem.json.properties.data = selfJson.refs[refId];
            };

            selfItem.json.properties.data.infoData.status = 'init';
            getNodeData(selfItem.json.properties.data, selfItem.json);
          };
        });

        updateJSON(selfJson);
      };

      var dupRemove = function(arr, isNotReverse) {
        var result = [];
        var ids = [];

        if (!!!isNotReverse) {
          // 相同id的节点最终显示后面的状态
          arr.reverse();
        };

        arr.map(function(item) {

          // 不存在才加入结果集
          if (ids.indexOf(item.id) === -1) {
            result.push(item);
            ids.push(item.id);
          };
        });

        return result;
      };

      // 转换json字符串 , 组装完整的json数据
      var quneeParseNodeJSON = function(nodeList, nodeStatusList) {
        var nodeJSON;

        if (typeof nodeList === 'string') {
          nodeJSON = JSON.parse(nodeList);
        } else {
          nodeJSON = nodeList;
        };

        // 判断节点状态列表内是否有数据 没有则代表初始化状态
        if (!!nodeStatusList) {

          for (var key in nodeJSON) {

            if (key === 'groups') {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(group) {

                  // 循环组内的节点状态
                  group.nodes.map(function(node) {

                    if (node.id === (item.node_id || item.id)) {
                      node.infoData.status = nodeStatusMap[item.status] || 'init';
                    };

                    node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                  });
                });
              });
            } else {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(node) {

                  if (node.id === (item.node_id || item.id)) {
                    node.infoData.status = nodeStatusMap[item.status] || 'init';
                  };

                  node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                });
              });
            }
          };
        } else {

          for (var key in nodeJSON) {
            nodeJSON[key].map(function(node) {
              node.infoData.status = 'init';
              node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
            });
          };
        };
        return nodeJSON;
      };

      var updateQuneeStateBtn = function() {
        switch ($scope.quneeState) {

          // 初始化
          case 'init':
          console.log('init');
            // $node.find('.htrd-l-bg-black i').removeClass().addClass('htrd-icon-check');
            // $node.find('.htrd-l-bg-black i').removeClass().addClass('htrd-icon-random');
            // $node.find('.htrd-l-bg-black i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click')
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-continue').hide();
            $node.find('.qunee-check').show();
            $node.find('.htrd-c-button-group').show();
            $scope.stateConfig = {
              check: true,
              start: true,
              continue: false,
              pause: true,
              quit: false,
            };
            break;

          // 检测中
          case 'check':
          console.log('check');
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');

            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');

            $node.find('.qunee-start').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click');

            $node.find('.qunee-pause').hide();
            $node.find('.qunee-continue').hide();
            $node.find('.htrd-c-button-group').show();

            ParseMapServ.setItem(processId, 'check','lastState');

            $scope.stateConfig = {
              check: false,
              start: false,
              pause: false,
              continue: false,
              quit: false,
            };
            break;

          // 检测异常
          case 'checkError':
          console.log('checkError');
            $node.find('.qunee-check').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            // $node.find('.qunee-start').addClass('default btn-outline');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-stop-click')
            $node.find('.qunee-pause').hide();
            // $node.find('.qunee-continue').hide();
            $node.find('.htrd-c-button-group').show();
            // $node.find('.qunee-start').show();

            $scope.stateConfig = {
              check: true,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };

            if (!$node.find('.qunee-start').is(":hidden")) {
              $node.find('.qunee-start').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
            };

            if (!$scope.init) {
              // AlertServ.showError('检测异常');
            } else {
              $scope.init = false;
            };
            break;

          // 检测完成
          case 'checkSuccess':
          console.log('checkSuccess');
            $node.find('.htrd-c-button-group').show()
            $scope.stateConfig = {
              check: true,
              start: true,
              continue: true,
              pause: false,
              quit: false
            };

            if ($scope.isCheck) {
              $node.find('.qunee-pause').hide();

              if (!$node.find('.qunee-start').is(":hidden")) {
                $node.find('.qunee-start').removeClass('default btn-outline').attr("disabled", false);
                $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random');
              };

              if (!$node.find('.qunee-continue').is(":hidden")) {
                $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
                $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
              };

              if (!$scope.init) {
                $node.find('.qunee-continue').hide();
                $node.find('.qunee-start').show();
              } else {
                $node.find('.qunee-continue').hide();
                $node.find('.qunee-start').show();
                $scope.init = false;
              };
              $node.find('.qunee-check').removeClass('default btn-outline').attr("disabled", false);
              $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');

              $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');
            } else {
              $scope.stateConfig = {
                check: false,
                start: true,
                pause: true,
                continue: true,
                quit: true
              };

              $node.find('.qunee-start').hide();
              $node.find('.qunee-continue').hide();
              $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
              $node.find('.qunee-quit').show().removeClass('default btn-outline').attr("disabled", false);
              $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
              $node.find('.qunee-pause').show().removeClass('default btn-outline').attr("disabled", false);
              $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            };
            break;

          // 等待执行 / 执行中 / 继续执行
          case 'running':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-pause').show();
            $node.find('.qunee-continue').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: true,
              quit: true
            };
            ParseMapServ.setItem(processId, 'running', 'lastState');
            break;

          // 暂停
          case 'pause':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: true,
              quit: true
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          case 'waitUserConfirm':

            $node.find('.qunee-check').addClass('default btn-outline');
            $node.find('.qunee-pause').removeClass('default btn-outline');
            $node.find('.qunee-continue').removeClass('default btn-outline');
            $node.find('.qunee-quit').removeClass('default btn-outline');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: true,
              quit: true
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          case 'parseError':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: true,
              quit: true
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          case 'runError':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
            $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          // 手工终止
          case 'manualQuit':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
            $node.find('.qunee-continue').hide();
            $node.find('.qunee-pause').show();
            $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };

            if ($scope.quitState) {
              $node.find('.qunee-start').hide();
              // $node.find('.qunee-pause').hide();
              $node.find('.qunee-continue').hide();

              if ($scope.quitState === 'start') {
                $node.find('.qunee-start').show().addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click')
              }
              else if ($scope.quitState === 'continue') {
                $node.find('.qunee-continue').show().addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
              }
              else if ($scope.quitState === 'pause'){
                $node.find('.qunee-pause').show().addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
              };
            } else {

              if (!$node.find('.qunee-start').is(":hidden")) {
                $node.find('.qunee-start').addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click');
              };

              if (!$node.find('.qunee-continue').is(":hidden")) {
                $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
              };

              if (!$node.find('.qunee-pause').is(":hidden")) {
                $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
                $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
              };
            };
            ParseMapServ.setItem(processId, 'manualQuit','lastState');
            break;


          // 全部执行成功
          case 'runSuccess':
            $node.find('.qunee-start').hide();
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');

            if (!$node.find('.qunee-continue').is(":hidden")) {
              $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
            };
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };

            strapModal = DialogServ.modal({
              'scope': $scope,
              'templateUrl': 'view/console/modal/quneeEditorExecResult.html'
            });
            strapModal.$promise.then(strapModal.show);
            break;

          case 'runSuccessAndNodeError':

            // AlertServ.showSuccess('流程执行成功了');
            $node.find('.qunee-start').hide();
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop-click');

            if (!$node.find('.qunee-continue').is(":hidden")) {
              $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
              $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');
            };
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };

            strapModal = DialogServ.modal({
              'scope': $scope,
              'templateUrl': 'view/console/modal/quneeEditorExecResult.html'
            });
            strapModal.$promise.then(strapModal.show);
            break;

          // 执行错误
          case 'error':
            $node.find('.qunee-check').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: false,
              quit: true
            };
            break;

          case 'runTimeout':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: false,
              start: false,
              continue: false,
              pause: false,
              quit: false
            };
            $timeout.cancel(quneeStart);
            ParseMapServ.setItem(processId, 'pause', 'lastState');
            break;

          // 执行超时
          case 'overtime':
            $node.find('.qunee-check').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-stop');
            $node.find('.qunee-continue').show();
            $node.find('.qunee-pause').hide();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: true,
              pause: false,
              quit: true
            };
            break;

          case 'waitConfirmOrSubmit':
            $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
            $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check');
            $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
            $node.find('.qunee-quit').removeClass('default btn-outline').attr("disabled", false);
            $node.find('.qunee-quit i').removeClass().addClass('htrd-icon-start');
            $node.find('.qunee-continue').hide();
            $node.find('.qunee-pause').show();
            $node.find('.qunee-start').hide();
            $scope.stateConfig = {
              check: true,
              start: false,
              continue: false,
              pause: false,
              quit: true
            };

            ParseMapServ.setItem(processId, 'waitConfirmOrSubmit', 'lastState');
            break;
          default:
        }
      };

      var toggleRadio = function(isActive) {
        $scope.userConfirmModel = $scope.userConfirmModel || {};
        $scope.userConfirmModel.is_exec = isActive;
      };

      var toggleTakeRadio = function(isActive) {
        $scope.userEditorTakeOverModel = $scope.userEditorTakeOverModel || {};
        $scope.userEditorTakeOverModel.check = isActive;
      };

      var socketPullData = function(data) {
        $node.trigger('qunee.stateChange', data);
      };

      var getQuneeNodeInfo = function(data) {
        $scope.$apply(function () {
          $scope.historyListState = false;
          $scope.processInfoState = false;
          $scope.nodeInfoState = true;
        });
      };

      var getQuneeProcessInfo = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeInfo({
          id: processId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.processInfo = ret.results;
          } else {

          };
        });
      };

      var getQuneeHistoryList = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeHistoryList({
          id: processId
        })
        .then(function(ret) {

          if (ret.status === 200) {

            // 格式化时间
            ret.results.map(function(item, index) {
              item.started_at = DateParseServ.dateParse(item.started_at);
              item.resultStatusStr = quneeExecStatus[item.result_status];
            });

            $scope.historyList = ret.results;
          } else {
            $scope.historyList = [];
            AlertServ.showError(ret.msg);
          };
        });
      };

      var getUserList = function() {
        $scope.userList = [
          {
            id: 1,
            title: '张健'
          }
        ];

        // ManagerProcessQuneeServ.getUserList()
        // .then(function(ret) {
        //
        //   if (ret.status === 200) {
        //     $scope.userList = [];
        //     ret.results.data.map(function(item, index) {
        //       $scope.userList.push({
        //         id: item.id,
        //         title: item.username
        //       });
        //     });
        //   }
        // });
      };

      var activeUser = function(item) {
        $scope.userConfirmModel.user_id = item.id;
      };

      // 用户用户确认/重做弹框
      var submitUserConfirm = function() {
        delete $scope.userConfirmModel.errerMsg;
        $scope.userConfirmModel.id = execId;
        // $scope.userConfirmModel.node_id =
        $scope.userConfirmModel.is_exec = $scope.userConfirmModel.is_exec;

        if (!!!$scope.userConfirmModel.user_id) {
          $scope.userConfirmModel.errerMsg = '请选择用户';
          return false;
        };

        if (!!!$scope.userConfirmModel.password) {
          $scope.userConfirmModel.errerMsg = '请输入密码';
          return false;
        };

        // 选中不认可 同时 未填写不认可理由
        if (!!!$scope.userConfirmModel.is_exec && !!!$scope.userConfirmModel.result_info) {
          $scope.userConfirmModel.errerMsg = '请输入不认可理由';
          return false;
        };

        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.submitManagerProcessQuneeUserConfirm($scope.userConfirmModel)
        .then(function(ret) {

          if (ret.status === 200) {
            // AlertServ.showSuccess(ret.msg);
            strapModal.hide();
            $scope.selectDefaultText = '请选择用户';


            if (!!$scope.userConfirmModel.is_exec) {
              $scope.quitState = 'running';
              $scope.quneeState = 'running';
              $scope.socketPullData($scope.quneeState);

              // 清空dialog 下次用户确认继续可以显示
              strapModal = null;
              $scope.userConfirmModel = {};
            } else {
              $scope.quneeState = 'manualQuit';
              $scope.socketPullData('noApproval');
            };
            updateQuneeStateBtn();
          } else {
            $scope.userConfirmModel.errerMsg = ret.msg || '密码错误, 请重试';
            // AlertServ.showError();
          };
        });
      };

      // 用户接管
      var submitEditorTakeOver = function() {
        var data = {
          id: execId,
          status: $scope.userEditorTakeOverModel.check,
          result_info: $scope.userEditorTakeOverModel.remark.trim()
        };
        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.ManagerProcessQuneeManualNozzleNode(data)
        .then(function(ret) {

          if (ret.status === 200) {
            AlertServ.showSuccess(ret.msg);
            strapModal.hide();
            $scope.userEditorTakeOverModel = {
              check: 1
            };
            $scope.quneeState = 'manualQuit';
            updateQuneeStateBtn();

            if (!$node.find('.qunee-start').is(":hidden")) {
              ParseMapServ.setItem(processId, 'start', 'quitState');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              ParseMapServ.setItem(processId, 'continue', 'quitState');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              ParseMapServ.setItem(processId, 'pause', 'quitState');
            };

            // if (!!$scope.userEditorTakeOverModel.check) {
            //   $scope.socketPullData('takeOverSucc');
            // } else {
            //   $scope.socketPullData('takeOverError');
            // };
          } else {
            AlertServ.showError(ret.msg);
          }
        });
      };



      // 手动终止确认
      var submitProcessQuit = function() {
        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.ManagerProcessQuneeQuit({
          id: execId,
          result_info: $scope.userEditorQuitModel.remark
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.userEditorQuitModel = {};
            strapModal.hide();
            $timeout.cancel(quneeStart);
            $scope.quneeState = 'manualQuit';

            if (!$node.find('.qunee-start').is(":hidden")) {
              ParseMapServ.setItem(processId, 'start', 'quitState');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              ParseMapServ.setItem(processId, 'continue', 'quitState');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              ParseMapServ.setItem(processId, 'pause', 'quitState');
            };

            AlertServ.showSuccess(ret.msg || '终止成功');
            updateQuneeStateBtn();
            $scope.socketPullData('quit');
          } else {
            AlertServ.showError(ret.msg);
          };
        });
      };


      // 初始化页面log
      var getManagerProcessQuneeLogList = function(execId) {
        ManagerProcessQuneeServ.getManagerProcessQuneeLogList({
          id: execId
        })
        .then(function(ret) {

          if (ret.status === 200) {

            if ($scope.logList.length > 0) {
              var logList = $scope.logList.concat(ret.results);
              $scope.logList = dupRemove(logList, true);
            } else {
              $scope.logList = ret.results;
            };

            $scope.logList.map(function(item) {
              item.created_at = DateParseServ.dateParse(item.created_at);
            });
          } else {
            AlertServ.showError(ret.msg);
          };
        });
      };

      // 获取当前流程节点json数据以及状态
      var getQuneeStateAndData = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeStateAndData({
          id: processId
        })
        .then(function(ret) {
          var quneeState;

          if (ret.status === 200) {

            // 模拟点击执行后 数据返回的状态为 2
            // var pl_ex_id = ParseMapServ.getItem(processId, 'process');
            var pl_ex_id = execId;

            // 获取1级状态 0 基本 1 检测中 2 执行中
            quneeState = ret.results.status;
            // ManagerProcessQuneeServ.getNodeJsonTest()
            // .then(function(result) {
              // 模拟读nodeJson
              // ret.results.pipeline = result;
            switch (quneeState) {

              // 如果是默认状态 则判断chekced内的状态
              case 0:
                // var pl_ex_id = ParseMapServ.getItem(processId, 'process') || ret.results.exec_pipeline_id;
                var pl_ex_id = ret.results.exec_pipeline_id;

                // 判断是否检测过
                if (!!ret.results.checked) {
                  $scope.init = true;

                  if (!!ret.results.checked.ended_at) {
                    $scope.lastCheckDateStr = '上次检测时间: ' + ret.results.checked.ended_at.replace('T', ' ').replace('Z','');
                  };

                  $scope.lastCheckStatus = ret.results.checked.status;

                  $scope.pipeline = ret.results.pipeline;

                  console.log(JSON.parse($scope.pipeline));

                  // 保存在全局的节点列表
                  $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);
                  $scope.initEditor();

                  // quneeStateMap
                  // if (typeof ret.results.checked.status === 'number') {
                  //   $scope.quneeState = quneeStateMap[ret.results.checked.status];
                  // } else {
                  //   $scope.quneeState = ret.results.checked.status || 'init';
                  // };
                  $scope.quneeState = 'init';

                  if (pl_ex_id) {
                    // $scope.quitState = ParseMapServ.getItem(processId, 'quitState');
                    // $scope.quneeState = 'init';
                    $scope.quitState = 'manualQuit';
                    $scope.quneeState = 'init'
                  };

                } else {
                  $scope.pipeline = ret.results.pipeline;

                  // 保存在全局的节点列表中
                  $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline);

                  $scope.initEditor();
                  $scope.quitState = ParseMapServ.getItem(processId, 'lastState');
                  $scope.quneeState = 'init';
                };
                updateQuneeStateBtn();
                break;

              // 如果是检测中 则状态为检测中
              case 1:
                var groupNodes = [];
                var selfJson;

                if (typeof ret.results.status === 'number') {
                  $scope.quneeState = quneeStateMap[ret.results.status];
                } else {
                  $scope.quneeState = ret.results.status;
                };

                $scope.pipeline = ret.results.pipeline;
                $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);
                $scope.initEditor(function() {

                  // 先获取全部node
                  selfJson = JSON.parse($scope.getChartJSON());

                  // 先渲染socket推送过来的节点
                  selfJson && selfJson.datas.map(function(selfItem, index) {

                    if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                      groupNodes.push({
                        index: index,
                        item: selfItem,
                        ref: selfItem.json.properties.data.$ref
                      });
                    };
                  });
                  var resukt_nodeList = dupRemove($scope.changeNodeList);
                  resukt_nodeList.map(function(node, index) {

                    // 更新节点数据 只会改变单个节点
                    selfJson.datas.map(function(selfItem, index) {

                      // 更新普通节点
                      if (selfItem._className === 'Q.Node') {
                        var refId;

                        // 判断id是否存在 不存在则为组
                        if (!!!selfItem.json.properties.data.id) {
                          refId = selfItem.json.properties.data.$ref;
                          selfItem.json.properties.data = selfJson.refs[refId];
                        };

                        if (selfItem.json.properties.data.id === node.id) {
                          selfItem.json.properties.data.infoData.status = node.status;
                          updateNode = selfItem.json.properties.data;
                          getNodeData(selfItem.json.properties.data, selfItem.json);
                          $scope.isShowDialog = (nodeStatusMap[node.status] === 'waitUserConfirm' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');

                          if ($scope.isShowDialog) {
                            $scope.quneeState = 'waitConfirmOrSubmit';
                            $scope.socketPullData('pause');
                          };
                        };
                      };
                    });
                  });
                  updateJSON(selfJson);
                  $scope.quneeState = 'check';
                  $scope.socketPullData('check');
                  updateQuneeStateBtn();
                });
                break;

              // 如果是执行中 调用其他接口获取执行的具体状态
              case 2:
                var groupNodes = [];
                var selfJson;
                execId = ret.results.exec_pipeline_id;
                $scope.pipeline = ret.results.pipeline;
                $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);

                var lastState = nodeStatusMap[ret.results.checked.status];

                if (ret.results.checked.status === 5) {
                  lastState = 'running';
                };

                $scope.lastState = lastState;

                // 初始化节点流程图
                $scope.initEditor(function() {

                  // 先获取全部node
                  selfJson = JSON.parse($scope.getChartJSON());

                  // 先渲染socket推送过来的节点
                  selfJson && selfJson.datas.map(function(selfItem, index) {

                    if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                      groupNodes.push({
                        index: index,
                        item: selfItem,
                        ref: selfItem.json.properties.data.$ref
                      });
                    };
                  });
                  var resukt_nodeList = dupRemove($scope.changeNodeList);
                  resukt_nodeList.map(function(node, index) {
                    selfJson.datas.map(function(selfItem, index) {

                      // 更新普通节点
                      if (selfItem._className === 'Q.Node') {

                        var refId;

                        // 判断id是否存在 不存在则为组
                        if (!!!selfItem.json.properties.data.id) {
                          refId = selfItem.json.properties.data.$ref;
                          selfItem.json.properties.data = selfJson.refs[refId];
                        };

                        if (selfItem.json.properties.data.id === node.id) {
                          selfItem.json.properties.data.infoData.status = node.status;
                          updateNode = selfItem.json.properties.data;
                          getNodeData(selfItem.json.properties.data, selfItem.json);
                        };
                      };
                    });
                  });
                  updateJSON(selfJson);
                  $scope.getQuneeExecState(ret.results.exec_pipeline_id);

                  if (!!ret.results.exec_pipeline_id) {
                    $scope.getManagerProcessQuneeLogList(ret.results.exec_pipeline_id);
                  };
                });
                break;
              default:
            };
            // });
          } else {

          };
        });
      };

      // 获取执行的具体状态
      var getQuneeExecState = function(execId) {
        ManagerProcessQuneeServ.getManagerProcessQuneeExecState({
          id: execId
        })
        .then(function(ret) {

          if (ret.status === 200) {

            if (ret.results.result_status === 13) {
              $scope.lastState = 'pause';
              $scope.quneeState = 'pause';
            }
            else if (ret.results.result_status === 6){

              if ($scope.lastState !== 'check') {
                $scope.quneeState = 'pause';
              };

              $scope.lastState = 'pause';
            }
            else if (ret.results.result_status === 7){

              // 执行中 但节点错误
              $scope.quneeState = 'pause';
              $scope.lastState = 'parseError';
            }
            else if (ret.results.result_status === 10){

              // 执行中 但节点错误
              $scope.quneeState = 'pause';
              $scope.lastState = 'waitUserConfirm';
            };

            $scope.socketPullData($scope.lastState);
            updateQuneeStateBtn();

            // 模拟保存上次执行后的实际状态 执行中 / 暂停
            var lastState = ParseMapServ.getItem(processId, 'lastState');
            var result_exec_nodes = [];
            $scope.quitState = ParseMapServ.getItem(processId, 'quitState');

            if (lastState) {
              ret.results.status = lastState;
              $scope.quneeState = ret.results.status;
            } else {

              if (typeof ret.results.status === 'number') {
                $scope.quneeState = runningMap[ret.results.status] || 'running';
              } else {
                $scope.quneeState = ret.results.status;
              };
            };

            ParseMapServ.setItem(processId, ret.results.pl_ex_id, 'process');

            // 去重获取最终结果
            var resukt_nodeList = dupRemove($scope.changeNodeList);

            // 去除socket中存在的节点 不在重复渲染
            ret.results.exec_nodes.map(function(item, index) {

              resukt_nodeList.map(function(socketItem) {

                if (item.node_id === socketItem.id) {
                  // 删除http中socket存在的节点
                  ret.results.exec_nodes.splice(index, 1);
                };
              });
            });

            // [0,5] + [1,2,3,4] = [0,1,2,3,4,5]
            result_exec_nodes = ret.results.exec_nodes.concat(resukt_nodeList);

            if (!!result_exec_nodes && result_exec_nodes.length > 0) {
              var groupNodes = [];
              var selfJson = JSON.parse($scope.getChartJSON());

              selfJson.datas.map(function(selfItem, index) {

                if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                  groupNodes.push({
                    index: index,
                    item: selfItem,
                    ref: selfItem.json.properties.data.$ref
                  });
                };
              });

              result_exec_nodes.map(function(node, index) {
                selfJson.datas.map(function(selfItem, index) {

                  // 更新普通节点
                  if (selfItem._className === 'Q.Node') {

                    var refId;

                    // 判断id是否存在 不存在则为组
                    if (!!!selfItem.json.properties.data.id) {
                      refId = selfItem.json.properties.data.$ref;
                      selfItem.json.properties.data = selfJson.refs[refId];
                    };

                    if (selfItem.json.properties.data.id === node.node_id) {
                      selfItem.json.properties.data.infoData.status = node.status;
                      updateNode = selfItem.json.properties.data;
                      getNodeData(selfItem.json.properties.data, selfItem.json);
                    };
                  };
                });
              });
              updateJSON(selfJson);
            };

            updateQuneeStateBtn();
          } else {

          };
        });
      };

      // 获取流程节点
      var getQuneeState = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeState()
        .then(function(result) {
          if (result.status === 200) {
            $scope.quneeState = result.results.state;
            updateQuneeStateBtn();
          };
        });
      };

      var onStateChange = function(evt, data) {

        // 所有标识状态的集合
        var tagStatusMap = {
          requesting: {
            status: 'qunee-status label label-info',
            text: '正在请求中'
          },

          check: {
            status: 'qunee-status label label-info',
            text: '流程检测中'
          },

          checkSuccess: {
            status: 'qunee-status label label-success bg-green',
            text: '检测成功'
          },

          checkError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          running: {
            status: 'qunee-status label label-info',
            text: '流程执行中'
          },

          runError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          pause: {
            status: 'qunee-status label label-info',
            text: '流程已暂停'
          },

          parseError: {
            status: 'qunee-status label label-danger',
            text: '执行错误'
          },

          st_pausing: {
            status: 'qunee-status label label-info',
            text: '流程已暂停'
          },

          continue: {
            status: 'qunee-status label label-info',
            text: '流程执行中'
          },

          quit: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止',
            processQuit: true
          },

          manualQuit: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止',
            processQuit: true
          },

          st_stopping: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止',
            processQuit: true
          },

          runSuccess: {
            status: 'qunee-status label label-success bg-green',
            text: '流程执行成功',
            processQuit: true
          },

          runSuccessAndNodeError: {
            status: 'qunee-status label label-danger ',
            text: '流程执行完成但节点有错误',
            processQuit: true
          },

          noApproval: {
            status: 'qunee-status label label-danger',
            text: '不认可',
            processQuit: true
          },

          takeOverSucc: {
            status: 'qunee-status label label-success bg-green',
            text: '手工接管后的执行结果：成功',
            processQuit: true
          },

          takeOverError: {
            status: 'qunee-status label label-danger',
            text: '手工接管后的执行结果：失败',
            processQuit: true
          },

          waitUserConfirm: {
            status: 'qunee-status label label-info',
            text: '等待用户确认'
          }
        };

        var status = tagStatusMap[data].status;
        var text = tagStatusMap[data].text;
        $scope.processQuit = !!tagStatusMap[data].processQuit;
        console.log('$scope.processQuit', $scope.processQuit);
        $node.find('.qunee-status').removeClass().addClass(status);
        $node.find('.qunee-status').text(text);
      };

      // 推送消息
      var onPushNodeData = function(data) {

        // 保存组内节点
        var groupNodes = [];
        var selfJson = JSON.parse($scope.getChartJSON());

        // 判断是否去组内去找
        var flag = true;
        // $scope.$apply(function() {

        if (!!data.log) {
          data.log.created_at = DateParseServ.dateParse(data.log.created_at);
          $scope.logList.push(data.log);
          $timeout(function() {
            var scrollTop = $node.find('.htrd-c-qunee-log')[0].scrollHeight;
            $node.find(".htrd-c-qunee-log").scrollTop(scrollTop);
          }, 1000);
        };

        if (!!data.node) {
          selfJson && selfJson.datas.map(function(item, index) {
            var model = item.json.properties.data;

            if (model.id === data.node.id) {

              if (model.infoData.type === 'startNode' && model.infoData.status === 6) {
                $scope.quneeState = 'running';

                // 改变流程状态标示的状态
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();
              };

              flag = false;
            };
          });

          // 判断是否在group内
          if (flag) {
            $scope.nodeList && $scope.nodeList.groups.map(function(group) {

              group.nodes.map(function(item) {
                var model = item.infoData;

                if (data.node.id === item.id) {

                  if (quneeRefTypeMap[item.infoData.ref_type] === 'startNode' && data.node.status === 6) {
                    $scope.quneeState = 'running';

                    // 改变流程状态标示的状态
                    $scope.socketPullData($scope.quneeState);
                    updateQuneeStateBtn();
                  };
                };
              });
            });
          };
          $scope.changeNodeList.push(data.node);
        };

        if (!!selfJson) {
          selfJson.datas.map(function(selfItem, index) {

            if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
              groupNodes.push({
                index: index,
                item: selfItem,
                ref: selfItem.json.properties.data.$ref
              });
            };
          });

          if (data.node) {
            var nodeFlag = true;

            // 更新节点数据 只会改变单个节点
            selfJson.datas.map(function(selfItem, index) {

              // 更新普通节点
              if (selfItem._className === 'Q.Node') {
                var refId;

                // console.log('selfItem', selfItem);

                // 判断id是否存在 不存在则为组
                if (!!!selfItem.json.properties.data.id) {
                  refId = selfItem.json.properties.data.$ref;
                  selfItem.json.properties.data = selfJson.refs[refId];
                };

                if (selfItem.json.properties.data.id === data.node.id) {
                  selfItem.json.properties.data.infoData.status = data.node.status;
                  updateNode = selfItem.json.properties.data;
                  // console.log('getNodeData');

                  console.log('selfItem.json.properties', selfItem.json.properties);
                  console.log('data.node', data.node);
                  getNodeData(selfItem.json.properties.data, selfItem.json);
                  $scope.isShowDialog = (nodeStatusMap[data.node.status] === 'waitUserConfirm' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');
                  nodeFlag = false;

                  if ($scope.isShowDialog) {
                    $scope.quneeState = 'waitConfirmOrSubmit';
                    $scope.socketPullData('pause');
                  };
                };
              };
            });


            // console.log('end selfJson', selfJson);

            updateJSON(selfJson);

            //console.log(JSON.parse($scope.getChartJSON()));

            if ($scope.isShowDialog) {
              $scope.userConfirmModel = $scope.userConfirmModel || {};
              $scope.userConfirmModel.node_id = updateNode.id;
              $scope.userConfirmModel.is_exec = 1;

              // if (!!!strapModal) {
              //   strapModal = DialogServ.modal({
              //     'scope': $scope,
              //     'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
              //   });
              //   strapModal.$promise.then(strapModal.show);
              // };
            };
          };

          if (typeof data.status === 'number') {
            $scope.quneeState = nodeStatusMap[data.status];

            if (data.status === 8) {
              $scope.socketPullData('runError');
            };

            if (data.status === 9) {
              $scope.socketPullData('runSuccess');
            };

            if (data.status === 11) {
              $scope.quitState = 'pause';
              $scope.quneeState = 'manualQuit';
              $scope.socketPullData('manualQuit');
            };

            // 正在检测
            if (data.status === 0) {

              if (data.check_status === 1) {
                $scope.quitState = 'running';
                $scope.quneeState = 'check';
              };

              if (data.check_status === 5) {

                // 单独检测
                $scope.isCheck = true;
                $scope.quneeState = 'checkSuccess';
              };

              if (data.check_status === 2) {

                // 单独检测
                $scope.isCheck = true;
                $scope.quneeState = 'checkError';
              };

              $scope.socketPullData($scope.quneeState);
            };

            // 执行中
            if (data.check_status === 5) {

              if (data.status === 6) {

                // 是执行 -> 检测
                $scope.isCheck = false;
                $scope.quneeState = 'running';
              }
              else if (data.status === 0){

                // 单独检测
                $scope.isCheck = true;
                $scope.quneeState = 'checkSuccess';

                // 代表此时是检测完成
                if (!!data.check_result && !!(data.check_result.type === 'EC')) {
                  $scope.hostErrorCount = data.check_result.host_err;
                  $scope.scriptErrCount = data.check_result.script_err;
                  $scope.$apply(function() {
                    $scope.lastCheckDateStr = '上次检测时间: ' + data.check_result.ended_at.replace('T', ' ').replace('Z','');
                  });
                  $scope.checkErrorMsg = '检测成功';
                  strapModal = DialogServ.modal({
                    'scope': $scope,
                    'templateUrl': 'view/console/modal/quneeEditorCheckResult.html'
                  });
                  strapModal.$promise.then(strapModal.show);
                };
              }
              else if (data.status === 2) {
                $scope.hostErrorCount = data.check_result.host_err;
                $scope.scriptErrCount = data.check_result.script_err;
                $scope.$apply(function() {
                  $scope.lastCheckDateStr = '上次检测时间: ' + data.check_result.ended_at.replace('T', ' ').replace('Z','');
                });
                $scope.checkErrorMsg = '脚本错误 ' + $scope.scriptErrCount + ' 个, 主机错误' + $scope.hostErrorCount + ' 个';
                strapModal = DialogServ.modal({
                  'scope': $scope,
                  'templateUrl': 'view/console/modal/quneeEditorCheckResult.html'
                });
                strapModal.$promise.then(strapModal.show);
                $scope.quneeState = 'checkError';
              }
              else if (data.status === 7) {
                console.log('执行错误');

                // 执行错误
                $scope.quneeState = 'parseError';
                $scope.socketPullData($scope.quneeState);
              }
              else if (data.status === 10) {
                console.log('用户确认暂停');

                // 执行错误
                // $scope.quneeState = 'pause';
                $scope.socketPullData($scope.quneeState);
                strapModal = DialogServ.modal({
                  'scope': $scope,
                  'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
                });
                strapModal.$promise.then(strapModal.show);
                //$scope.quneeState = 'waitConfirmOrSubmit';
              }

              else if (data.status === 19) {
                console.log('用户确认不认可终止');

                $scope.quneeState = 'manualQuit';
                $scope.socketPullData('noApproval');
              }

              else if (data.status === 20) {
                console.log('执行完成但有错误');

                // 执行错误
                $scope.quneeState = 'runSuccessAndNodeError';
                $scope.socketPullData($scope.quneeState);
              }

              else if (data.status === 21) {
                console.log('手工接管后的执行结果：成功停止');

                // 执行错误
                $scope.quneeState = 'takeOverSucc';
                $scope.socketPullData($scope.quneeState);
              }

              else if (data.status === 22) {
                console.log('手工接管后的执行结果：失败停止');

                // 执行错误
                $scope.quneeState = 'takeOverError';
                $scope.socketPullData($scope.quneeState);
              };
            };

            if (data.check_status === 2) {

              if (data.status === 2) {
                $scope.quneeState = 'runError';
                $scope.socketPullData($scope.quneeState);
              };

              if (data.status === 7) {

                $scope.quneeState = 'checkError';
                $scope.socketPullData($scope.quneeState);
              };

              if (data.status === 0) {
                $scope.quneeState = 'checkError';
                $scope.hostErrorCount = data.check_result.host_err;
                $scope.scriptErrCount = data.check_result.script_err;
                $scope.$apply(function() {
                  $scope.lastCheckDateStr = '上次检测时间: ' + data.check_result.ended_at.replace('T', ' ').replace('Z','');
                });
                $scope.checkErrorMsg = '脚本错误 ' + $scope.scriptErrCount + ' 个, 主机错误 ' + $scope.hostErrorCount + ' 个';
                strapModal = DialogServ.modal({
                  'scope': $scope,
                  'templateUrl': 'view/console/modal/quneeEditorCheckResult.html'
                });
                strapModal.$promise.then(strapModal.show);
                $scope.socketPullData($scope.quneeState);
              };
            };

            if (data.status === 20 && data.check_status === 5) {

              // 流程执行成功但有错误
              $scope.quneeState = 'runSuccessAndNodeError';
              $scope.socketPullData($scope.quneeState);
            };
            updateQuneeStateBtn();
          };
        };
      };

      var onQuneeInfo = function(evt, data) {
        $scope.$apply(function() {
          $scope.processInfoState = !$scope.processInfoState;
          $scope.historyListState = false;
          $scope.nodeInfoState = false;
        });
      };

      var onQuneeHistory = function(evt, data) {
        $scope.$apply(function() {
          $scope.historyListState = !$scope.historyListState;
          $scope.processInfoState = false;
          $scope.nodeInfoState = false;
        });
      };

      // 检测
      var onQuneeCheck = function(evt, data) {

        console.log('检测')

        if ($scope.stateConfig.check) {
          $scope.quneeState = 'check';

          // 重置所有节点
          resetNodes();

          // 改变流程摁键组的状态
          updateQuneeStateBtn();

          // 改变流程状态标示的状态
          $scope.socketPullData('requesting');
          ManagerProcessQuneeServ.ManagerProcessQuneeCheck({
            id: processId
          })
          .then(function(ret) {

            if (ret.status !== 200) {
              // $scope.quneeState = 'checkSuccess';
              $scope.quneeState = 'checkError';
              // 改变流程状态标示的状态
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
            };
          });

        };
      };


      // 点击执行
      var onQuneeStart = function(evt, data) {

        if ($scope.stateConfig.start) {

          // 重置所有节点
          resetNodes();

          // 改变流程状态标示的状态
          $scope.socketPullData('requesting');
          $node.find('.qunee-start').addClass('default btn-outline').attr("disabled", true);
          $node.find('.qunee-start i').removeClass().addClass('htrd-icon-random-click');
          $node.find('.qunee-check').addClass('default btn-outline').attr("disabled", true);
          $node.find('.qunee-check i').removeClass().addClass('htrd-icon-check-click');
          ManagerProcessQuneeServ.ManagerProcessQuneeStart({
            id: processId
          })
          .then(function(ret) {

            if (ret.status === 200) {

              var updateNode;
              $node.find('.qunee-start').removeClass('default btn-outline').attr("disabled", false);
              $node.find('.htrd-l-bg-black i').removeClass().addClass('htrd-icon-random');
              ParseMapServ.setItem(processId, ret.results.pl_ex_id, 'process');
              execId = ret.results.pl_ex_id;
              $scope.stateConfig.start = !!!$scope.stateConfig.start;
              $scope.quneeState = 'check';

              // 改变流程状态标示的状态
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 暂停
      var onQuneePause = function(evt, data) {

        if ($scope.stateConfig.pause) {
          $scope.socketPullData('requesting');
          $node.find('.qunee-pause').addClass('default btn-outline').attr("disabled", true);
          $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause-click');

          if (!!!execId) {
            // execId = ParseMapServ.getItem(processId, 'process');
          };

          ManagerProcessQuneeServ.ManagerProcessQuneePause({
            id: execId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              $timeout(function() {
                $node.find('.qunee-pause').removeClass('default btn-outline').attr("disabled", false);
                $node.find('.qunee-pause i').removeClass().addClass('htrd-icon-pause');
                $scope.quneeState = 'pause';
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();
                // AlertServ.showSuccess(ret.msg);
              }, 2000);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 继续
      var onQuneeContinue = function(evt, data) {

        if ($scope.stateConfig.continue) {
          var updateNode;
          $scope.socketPullData('requesting');
          $node.find('.qunee-continue').addClass('default btn-outline').attr("disabled", true);
          $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
          ManagerProcessQuneeServ.ManagerProcessQuneeContinue({
            id: execId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              $scope.quneeState = 'running';
              // $timeout(function() {
              $node.find('.qunee-continue').removeClass('default btn-outline').attr("disabled", false);
              $node.find('.qunee-continue i').removeClass().addClass('htrd-icon-random-click');
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
              // }, 2000);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 终止
      var onQuneeQuit = function(evt, data) {

        if ($scope.stateConfig.quit) {

          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorQuit.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
      };

      // 重做本节点
      var onQuneeRestartSelfNode = function(evt, data) {
        console.log('$scope.processQuit', $scope.processQuit);

        // 流程已经终止了
        if ($scope.processQuit) {
          AlertServ.showSuccess('流程已结束 , 无法操作');
          return false;
        };

        $scope.isShowDialog = (!!(data.type === 'userConfirmNode' && data.status === 10));

        if ($scope.isShowDialog) {
          $scope.userConfirmModel = $scope.userConfirmModel || {};
          $scope.userConfirmModel.id = data.id;
          $scope.userConfirmModel.node_id = data.nodeId;
          $scope.toggleRadio(1);
        } else {
          ManagerProcessQuneeServ.ManagerProcessQuneeResetNode({
            id: execId,
            node_id: data.nodeId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              AlertServ.showSuccess('请求成功');
            } else {
              AlertServ.showError('请求失败');
            };
          });
        };
      };

      // 手工接管
      var onQuneeManualNozzleNode = function(evt, data) {
        console.log('$scope.processQuit', $scope.processQuit);

        // 流程已经终止了
        if ($scope.processQuit) {
          AlertServ.showSuccess('流程已结束 , 无法操作');
          return false;
        };

        if (!!!data.disabled) {
          $scope.userEditorTakeOverModel.id = data.id;
          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorTakeOver.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
      };

      // 切换日志显示状态
      var toggleLog = function() {
        $scope.logShowState = !!!$scope.logShowState;
      };

      var getNodeData = function(data, node, isGroup) {
        var type, status, info;

        if (isGroup) {
          type = quneeRefTypeMap[data.infoData.ref_type];

          if (node.status && typeof node.status === 'string') {
            status = node.infoData.status;
          } else {
            status = nodeStatusMap[node.status] || 'init';
          };
          info = $scope.statusNodeMap[type][status];
          data.image = info.icon;
          data.menuList = info.menuList;
          data.status = status;
          data.type = type;
        } else {
          type = data.infoData.type || quneeRefTypeMap[data.infoData.ref_type];

          if (data.infoData.status && typeof data.infoData.status === 'string') {
            status = data.infoData.status;
          } else {
            status = nodeStatusMap[data.infoData.status] || 'init';
          };
          info = $scope.statusNodeMap[type][status];

          if (info) {
            node.image = info.icon;
            node.menuList = info.menuList;
          };
        };
      };

      // 创建折线
      // from 起点
      // to终点
      // pathSegmentList 中间坐标
      var createEdge = function(graph, from, to, pathSegmentList) {
        var edge = graph.createEdge('edge', from, to);
        pathSegmentList && pathSegmentList.map(function(item) {
          edge.addPathSegment([item.x, item.y]);
        });
        return edge;
      };

      // 创建组节点
      var createGroup = function (groupData, expanded, graph) {
        var graph = graph || $window.editor.graph;
        expanded = expanded !== false;
        var group = graph.createGroup(groupData.name);

        group.expanded = expanded;
        var groupHandle = new Q.LabelUI(expanded ? "-" : "+");
        groupHandle.backgroundColor = "#2898E0";
        groupHandle.color = "#FFF";
        groupHandle.padding = new Q.Insets(0, 4);
        groupHandle.borderRadius = 0;
        groupHandle.position = Q.Position.RIGHT_TOP;
        groupHandle.anchorPosition = Q.Position.LEFT_TOP;
        groupHandle.type = "GroupHandle";
        groupHandle.reverseExpanded = function(evt){
            var g = this.parent.data;
            g.expanded = !g.expanded;
        }
        group.addUI(groupHandle, {
            property : "expanded",
            callback: function(value, ui){
              ui.data = value ? "-" : "+";
            }
        });
        return group;
      };

      // 解析json
      var translateToQuneeElements = function(json, graph){
          var map = {};
          var graph = graph || $window.editor.graph;

          // 创建普通节点
          if (json.nodes) {
              Q.forEach(json.nodes, function(data){
                  var node = graph.createNode(data.name, data.x || 0, data.y || 0);
                  getNodeData(data, node);
                  node.set("data", data);
                  map[data.id] = node;
              });
          };

          // 创建组
          if (json.groups) {
              Q.forEach(json.groups, function(data){
                  var group = createGroup(data, true, graph);
                  getNodeData(data, group);
                  data.nodes.map(function(item){

                    // 子组
                    var innerNode = graph.createNode(item.name, item.x, item.y);
                    getNodeData(item, innerNode);
                    innerNode.set("data", item);
                    map[item.id] = innerNode;
                    group.addChild(innerNode);
                  });

                  group.set("data", data);
                  map[data.id] = group;
              });
          };

          // 创建连线
          if (json.edges) {
              Q.forEach(json.edges, function(data){
                  var from = map[data.from];
                  var to = map[data.to];

                  if(!from || !to){
                      return;
                  };

                  // data.pathSegmentList = [
                  //   {
                  //     x: 100,
                  //     y: 200
                  //   }
                  // ];

                  var edge = createEdge(graph, from, to, data.infoData.pathList);
                  edge.set("data", data);
              }, graph);
          };
      };


      // 显示右侧信息
      var onShowNodeInfo = function(evt) {
        console.log('onShowNodeInfo');
        var data = evt.getData();
        var nodeId;

        // 是否点击到空白处
        if (!!!data) {
          $scope.$apply(function() {
            $scope.historyListState = false;
            $scope.processInfoState = false;
            $scope.nodeInfoState = false;
          });
        } else {

          if (data instanceof Q.Group) {
              var target = $window.editor.graph.hitTest(evt);

              if (target && target.type == "GroupHandle") {
                  target.reverseExpanded();
              } else {
                nodeId = data._n0w.data.id;
                $scope.nodeInfo = {
                  id: nodeId
                };

                $scope.$apply(function() {
                  $scope.historyListState = false;
                  $scope.processInfoState = false;
                  $scope.nodeInfoState = true;
                });
              }
          } else {
            nodeId = data._n0w.data.id;
            $scope.nodeInfo = {
              id: nodeId
            };

            $scope.$apply(function() {
              $scope.historyListState = false;
              $scope.processInfoState = false;
              $scope.nodeInfoState = true;
            });
          }
        };
      };

      var initQuneeEvent = function() {
        editor.graph.onclick = onShowNodeInfo;
      };

      // 获取加载完成的json
      var getChartJSON = function() {

        if (!!$window.editor) {
          return editor.graph.exportJSON(true, {space: '  '});
        } else {
          return null;
        };
      };

      var initEditor = function(callback) {
        console.log('editor')
        $node.find('.editor').graphEditor({
          callback: function(editor){
            // editor.graph.delayedRendering = true;
            translateToQuneeElements($scope.nodeList, editor.graph);
            editor.graph.moveToCenter();
            $window.editor = editor;
            var selfJson = JSON.parse($scope.getChartJSON());
            initQuneeEvent();
            $timeout(function () {
              editor.graph.zoomToOverview();
            }, 100);
            callback && callback();
          }
        });
      };

      // 局部刷新流程图
      var updateJSON = function(data) {
        editor.submitJSON(data);
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
        $window.$quneeNode = $node;
      };

      var bindListener = function() {
        $scope.getQuneeNodeInfo = getQuneeNodeInfo;
        $scope.getQuneeProcessInfo = getQuneeProcessInfo;
        $scope.getQuneeHistoryList = getQuneeHistoryList;
        $scope.getManagerProcessQuneeLogList = getManagerProcessQuneeLogList;
        $scope.getUserList = getUserList;
        $scope.createGroup = createGroup;
        $scope.translateToQuneeElements = translateToQuneeElements;
        $scope.initEditor = initEditor;
        $scope.updateJSON = updateJSON;
        $scope.getChartJSON = getChartJSON;
        $scope.initQuneeEvent = initQuneeEvent;
        $scope.toggleLog = toggleLog;
        $scope.getQuneeState = getQuneeState;
        $scope.getQuneeStateAndData = getQuneeStateAndData;
        $scope.getQuneeExecState = getQuneeExecState;
        $scope.submitUserConfirm = submitUserConfirm;
        $scope.activeUser = activeUser;
        $scope.submitEditorTakeOver = submitEditorTakeOver;
        $scope.submitProcessQuit = submitProcessQuit;
        $scope.socketPullData = socketPullData;
        $scope.toggleRadio = toggleRadio;
        $scope.toggleTakeRadio = toggleTakeRadio;

        // 监听qunee 所有事件
        $node.on('qunee.check', onQuneeCheck);
        $node.on('qunee.start', onQuneeStart);
        $node.on('qunee.pause', onQuneePause);
        $node.on('qunee.continue', onQuneeContinue);
        $node.on('qunee.quit', onQuneeQuit);
        $node.on('qunee.restartSelfNode', onQuneeRestartSelfNode);
        $node.on('qunee.manualNozzleNode', onQuneeManualNozzleNode);
        $node.on('qunee.stateChange', onStateChange);

        $node.on('qunee.info', onQuneeInfo);
        $node.on('qunee.history', onQuneeHistory);
      };

      var initPlugins = function() {
        $scope.logList = [];
        $scope.changeNodeList = [];

        // 保存当前流程id
        processId = $stateParams.id;
        $scope.processId = processId;

        // 初始化socket链接
        SocketServ.initSocket(processId);
        SocketServ.onMessage(onPushNodeData);
        SocketServ.onClose();
        SocketServ.onError();

        $timeout(function() {
          SocketServ.sendMessage('test')
        }, 20000)

        // 只监听跳转路由
        $rootScope.$on('$stateChangeStart', function() {

          // 如果状态不为终止 执行成功 的话 则清除执行id
          if ($scope.quneeState === 'manualQuit' || $scope.quneeState === 'execSuccess') {
            ParseMapServ.removeItem(processId, 'quitState');
            ParseMapServ.removeItem(processId, 'process');
          };
        });

        // execId = ParseMapServ.getItem(processId, 'process') || 0;


        $scope.selectDefaultText = '请选择用户';
        $scope.stateConfig = {
          check: true,
          start: true,
          pause: true,
          quit: true
        };

        // 用户接管表单参数
        $scope.userEditorTakeOverModel = {
          check: 1,
          resultQuery: true,
          remark: ''
        };

        $scope.userEditorQuitModel = {
          remark: ''
        };

        // 初始化参数
        $scope.historyListState = false;
        $scope.nodeInfoState = false;
        $scope.logShowState = false;
        $scope.processInfoState = false;

        // 所有节点状态字典
        ManagerProcessQuneeServ.getManagerProcessQuneeStateMap()
        .then(function(result) {
          $scope.statusNodeMap = result;
          $window.statusNodeMap = result;
          getQuneeStateAndData();
        });

        $scope.getUserList();
        $scope.getQuneeHistoryList();
        $scope.getQuneeProcessInfo();
        $node.find('.htrd-c-button-group').hide();
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'config': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/quneeEditer.html'
  };
}]);

// 拓扑图编辑
angular.module('HTRD_AutoConsole.A').directive('quneeEditerEdit',['$window', '$timeout', '$interval', '$stateParams', '$rootScope','ManagerProcessTreeServ','ManagerProcessQuneeServ','DialogServ', 'SocketServ', 'AlertServ', 'ParseMapServ', 'DateParseServ',
function($window, $timeout, $interval, $stateParams, $rootScope, ManagerProcessTreeServ,ManagerProcessQuneeServ,DialogServ, SocketServ, AlertServ, ParseMapServ, DateParseServ) {
  var link = function(s, e) {
      var $scope, $node;

      var nameInput = function(){
        $scope.nameInputShow = false;
      }

      var classifyInput = function(){
        $scope.classifyInputShow = false;
      }

      // 保存
      var processSave = function () {
        // processEditServ.saveProcessInfo($scope.processInfo)
        // .then(funcion(result){
        //   if(result.status === 200){
        //     AlertServ.showSuccess('保存成功');
        //   }
        // })
        console.log($scope.processInfo);
        AlertServ.showSuccess('保存成功');
      };

      //放弃
      var processAbandon = function(){
         strapModal = DialogServ.modal({
          'scope': $scope,
           'templateUrl': 'view/console/modal/abandonProcess.html'
         })
         strapModal.$promise.then(strapModal.show);
       }

      var giveUpBtn = function(){
       strapModal.hide();
       AlertServ.showSuccess('放弃成功');
     };

      var showProcessEdit = function() {
        $scope.processInfoState = !!!$scope.processInfoState;
        if($scope.processInfoState){
          $scope.nodeInfoState = false;
        }
        // 流程属性编辑
        $scope.$broadcast('qunee.process.edit', {
          processInfoState: $scope.processInfoState
        });
      };

      // 流程id
      var processId = 0;

      // 执行id
      var execId;

      // 如果状态为数字 则转换
      var quneeStateMap = {
        0: 'init', // 默认(1级分类)
        1: 'check', // 检测中(1级分类)
        2: 'exec', // 执行中(1级分类)
        3: 'checkError', // 检测异常(2级分类)
        4: 'checkSuccess', // 检测成功(2级分类)
        5: 'execSuccess' // 执行成功
      };

      // 执行中状态
      var runningMap = {
        0: 'pause',
        1: 'running'
      };

      // 执行中节点状态
      var runningNodeMap = {
        0: 'error',
        1: 'overtime',
        2: 'runningSuccess'
      };

      var quneeRefTypeMap = {
        1: 'basicNode',
        2: 'userConfirmNode',
        3: 'groupNode',
        4: 'startNode',
        5: 'endNode',
        6: 'closeNode',
        7: 'restartNode'
      };

      var resetNodes = function() {
        var refId;
        $scope.nodeList = quneeParseNodeJSON($scope.pipeline);

        // 先获取全部node
        selfJson = JSON.parse($scope.getChartJSON());
        selfJson.datas.map(function(selfItem, index) {

          // 更新普通节点
          if (selfItem._className === 'Q.Node') {

            if (!!!selfItem.json.properties.data.id) {
              refId = selfItem.json.properties.data.$ref;
              selfItem.json.properties.data = selfJson.refs[refId];
            };

            selfItem.json.properties.data.infoData.status = 'init';
            getNodeData(selfItem.json.properties.data, selfItem.json);
          };
        });

        updateJSON(selfJson);
      };

      var dupRemove = function(arr, isNotReverse) {
        var result = [];
        var ids = [];

        if (!!!isNotReverse) {
          // 相同id的节点最终显示后面的状态
          arr.reverse();
        };

        arr.map(function(item) {

          // 不存在才加入结果集
          if (ids.indexOf(item.id) === -1) {
            result.push(item);
            ids.push(item.id);
          };
        });

        return result;
      };

      // 转换json字符串 , 组装完整的json数据
      var quneeParseNodeJSON = function(nodeList, nodeStatusList) {
        var nodeJSON;

        if (typeof nodeList === 'string') {
          nodeJSON = JSON.parse(nodeList);
        } else {
          nodeJSON = nodeList;
        };

        // 判断节点状态列表内是否有数据 没有则代表初始化状态
        if (!!nodeStatusList) {

          for (var key in nodeJSON) {

            if (key === 'groups') {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(group) {

                  // 循环组内的节点状态
                  group.nodes.map(function(node) {
                    node.infoData.status = 'init';
                    node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                  });
                });
              });
            } else {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(node) {
                  node.infoData.status = 'init';
                  node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                });
              });
            }
          };
        } else {

          for (var key in nodeJSON) {
            nodeJSON[key].map(function(node) {
              node.infoData.status = 'init';
              node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
            });
          };
        };
        return nodeJSON;
      };

      var getQuneeProcessInfo = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeInfo({
          id: processId
        })
        .then(function(ret) {
          if (ret.status === 200) {
            console.log('流程info',ret);
            $scope.processInfo.name = ret.results.name;
            $scope.defaultText = ret.results.group_name;
            $scope.processInfo.group_name = $scope.defaultText;
          }
        });
      };

      var getUserList = function() {
        $scope.userList = [
          {
            id: 1,
            title: '张健'
          }
        ];

        // ManagerProcessQuneeServ.getUserList()
        // .then(function(ret) {
        //
        //   if (ret.status === 200) {
        //     $scope.userList = [];
        //     ret.results.data.map(function(item, index) {
        //       $scope.userList.push({
        //         id: item.id,
        //         title: item.username
        //       });
        //     });
        //   }
        // });
      };

      // var activeUser = function(item) {
      //   console.log('activeUser',item);
      //   $scope.userConfirmModel.user_id = item.id;
      // };

      // 获取当前流程节点json数据以及状态
      var getQuneeStateAndData = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeStateAndData({
          id: processId
        })
        .then(function(ret) {
          var quneeState;

          if (ret.status === 200) {

            console.log('ret'+ret+JSON.parse(ret.results.pipeline))

            // 模拟点击执行后 数据返回的状态为 2
            // var pl_ex_id = ParseMapServ.getItem(processId, 'process');
            var pl_ex_id = execId;

            // 获取1级状态 0 基本 1 检测中 2 执行中
            quneeState = ret.results.status;
            // ManagerProcessQuneeServ.getNodeJsonTest()
            // .then(function(result) {
              // 模拟读nodeJson
              // ret.results.pipeline = result;
            switch (quneeState) {

              // 如果是默认状态 则判断chekced内的状态
              case 0:
                // var pl_ex_id = ParseMapServ.getItem(processId, 'process') || ret.results.exec_pipeline_id;
                var pl_ex_id = ret.results.exec_pipeline_id;

                // 判断是否检测过
                if (!!ret.results.checked) {
                  $scope.init = true;

                  $scope.pipeline = ret.results.pipeline;

                  // 保存在全局的节点列表
                  $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);
                  $scope.initEditor();
                  $scope.quneeState = 'init';

                  if (pl_ex_id) {
                    // $scope.quitState = ParseMapServ.getItem(processId, 'quitState');
                    // $scope.quneeState = 'init';
                    $scope.quitState = 'manualQuit';
                    $scope.quneeState = 'init'
                  };

                } else {
                  $scope.pipeline = ret.results.pipeline;

                  // 保存在全局的节点列表中
                  $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline);

                  $scope.initEditor();
                  $scope.quneeState = 'init';
                };
                break;

              // 如果是检测中 则状态为检测中
              case 1:
                var groupNodes = [];
                var selfJson;

                if (typeof ret.results.status === 'number') {
                  $scope.quneeState = quneeStateMap[ret.results.status];
                } else {
                  $scope.quneeState = ret.results.status;
                };

                $scope.pipeline = ret.results.pipeline;
                $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);
                $scope.initEditor(function() {

                  // 先获取全部node
                  selfJson = JSON.parse($scope.getChartJSON());

                  // 先渲染socket推送过来的节点
                  selfJson && selfJson.datas.map(function(selfItem, index) {

                    if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                      groupNodes.push({
                        index: index,
                        item: selfItem,
                        ref: selfItem.json.properties.data.$ref
                      });
                    };
                  });
                  var resukt_nodeList = dupRemove($scope.changeNodeList);
                  resukt_nodeList.map(function(node, index) {

                    // 更新节点数据 只会改变单个节点
                    selfJson.datas.map(function(selfItem, index) {

                      // 更新普通节点
                      if (selfItem._className === 'Q.Node') {
                        var refId;

                        // 判断id是否存在 不存在则为组
                        if (!!!selfItem.json.properties.data.id) {
                          refId = selfItem.json.properties.data.$ref;
                          selfItem.json.properties.data = selfJson.refs[refId];
                        };

                        if (selfItem.json.properties.data.id === node.id) {
                          selfItem.json.properties.data.infoData.status = node.status;
                          updateNode = selfItem.json.properties.data;
                          getNodeData(selfItem.json.properties.data, selfItem.json);
                        };
                      };
                    });
                  });
                  updateJSON(selfJson);
                  $scope.quneeState = 'check';
                });
                break;

              // 如果是执行中 调用其他接口获取执行的具体状态
              case 2:
                var groupNodes = [];
                var selfJson;
                execId = ret.results.exec_pipeline_id;
                $scope.pipeline = ret.results.pipeline;
                $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline, ret.results.checked.check_nodes);

                // 初始化节点流程图
                $scope.initEditor(function() {

                  // 先获取全部node
                  selfJson = JSON.parse($scope.getChartJSON());

                  // 先渲染socket推送过来的节点
                  selfJson && selfJson.datas.map(function(selfItem, index) {

                    if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                      groupNodes.push({
                        index: index,
                        item: selfItem,
                        ref: selfItem.json.properties.data.$ref
                      });
                    };
                  });
                  var resukt_nodeList = dupRemove($scope.changeNodeList);
                  resukt_nodeList.map(function(node, index) {
                    selfJson.datas.map(function(selfItem, index) {

                      // 更新普通节点
                      if (selfItem._className === 'Q.Node') {

                        var refId;

                        // 判断id是否存在 不存在则为组
                        if (!!!selfItem.json.properties.data.id) {
                          refId = selfItem.json.properties.data.$ref;
                          selfItem.json.properties.data = selfJson.refs[refId];
                        };

                        if (selfItem.json.properties.data.id === node.id) {
                          selfItem.json.properties.data.infoData.status = node.status;
                          updateNode = selfItem.json.properties.data;
                          getNodeData(selfItem.json.properties.data, selfItem.json);
                        };
                      };
                    });
                  });
                  updateJSON(selfJson);
                  //$scope.getQuneeExecState(ret.results.exec_pipeline_id);
                });
                break;
              default:
            };
            // });
          } else {

          };
        });
      };

      // 获取执行的具体状态
      // var getQuneeExecState = function(execId) {
      //   ManagerProcessQuneeServ.getManagerProcessQuneeExecState({
      //     id: execId
      //   })
      //   .then(function(ret) {
      //
      //     if (ret.status === 200) {
      //
      //       if (ret.results.result_status === 13) {
      //         $scope.lastState = 'pause';
      //         $scope.quneeState = 'pause';
      //       }
      //       else if (ret.results.result_status === 6){
      //
      //         if ($scope.lastState !== 'check') {
      //           $scope.quneeState = 'pause';
      //         };
      //
      //         $scope.lastState = 'pause';
      //       }
      //       else if (ret.results.result_status === 7){
      //
      //         // 执行中 但节点错误
      //         $scope.quneeState = 'pause';
      //         $scope.lastState = 'parseError';
      //       };
      //
      //       // 模拟保存上次执行后的实际状态 执行中 / 暂停
      //       var lastState = ParseMapServ.getItem(processId, 'lastState');
      //       var result_exec_nodes = [];
      //       $scope.quitState = ParseMapServ.getItem(processId, 'quitState');
      //
      //       if (lastState) {
      //         ret.results.status = lastState;
      //         $scope.quneeState = ret.results.status;
      //       } else {
      //
      //         if (typeof ret.results.status === 'number') {
      //           $scope.quneeState = runningMap[ret.results.status] || 'running';
      //         } else {
      //           $scope.quneeState = ret.results.status;
      //         };
      //       };
      //
      //       ParseMapServ.setItem(processId, ret.results.pl_ex_id, 'process');
      //
      //       // 去重获取最终结果
      //       var resukt_nodeList = dupRemove($scope.changeNodeList);
      //
      //       // 去除socket中存在的节点 不在重复渲染
      //       ret.results.exec_nodes.map(function(item, index) {
      //
      //         resukt_nodeList.map(function(socketItem) {
      //
      //           if (item.node_id === socketItem.id) {
      //             // 删除http中socket存在的节点
      //             ret.results.exec_nodes.splice(index, 1);
      //           };
      //         });
      //       });
      //
      //       // [0,5] + [1,2,3,4] = [0,1,2,3,4,5]
      //       result_exec_nodes = ret.results.exec_nodes.concat(resukt_nodeList);
      //
      //       if (!!result_exec_nodes && result_exec_nodes.length > 0) {
      //         var groupNodes = [];
      //         var selfJson = JSON.parse($scope.getChartJSON());
      //
      //         selfJson.datas.map(function(selfItem, index) {
      //
      //           if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
      //             groupNodes.push({
      //               index: index,
      //               item: selfItem,
      //               ref: selfItem.json.properties.data.$ref
      //             });
      //           };
      //         });
      //
      //         result_exec_nodes.map(function(node, index) {
      //           selfJson.datas.map(function(selfItem, index) {
      //
      //             // 更新普通节点
      //             if (selfItem._className === 'Q.Node') {
      //
      //               var refId;
      //
      //               // 判断id是否存在 不存在则为组
      //               if (!!!selfItem.json.properties.data.id) {
      //                 refId = selfItem.json.properties.data.$ref;
      //                 selfItem.json.properties.data = selfJson.refs[refId];
      //               };
      //
      //               if (selfItem.json.properties.data.id === node.node_id) {
      //                 selfItem.json.properties.data.infoData.status = node.status;
      //                 updateNode = selfItem.json.properties.data;
      //                 getNodeData(selfItem.json.properties.data, selfItem.json);
      //               };
      //             };
      //           });
      //         });
      //         updateJSON(selfJson);
      //       };
      //     } else {
      //
      //     };
      //   });
      // };

      // 获取流程节点
      // var getQuneeState = function() {
      //   ManagerProcessQuneeServ.getManagerProcessQuneeState()
      //   .then(function(result) {
      //     console.log('流程节点',result);
      //     if (result.status === 200) {
      //       $scope.quneeState = result.results.state;
      //     };
      //   });
      // };

      // 推送消息
      var onQuneeInfo = function(evt, data) {
        $scope.$apply(function() {
          $scope.processInfoState = !$scope.processInfoState;
          $scope.nodeInfoState = false;
        });
      };

      var getNodeData = function(data, node, isGroup) {
        var type, status, info;

        if (isGroup) {
          type = quneeRefTypeMap[data.infoData.ref_type];
          status = 'init';
          info = $scope.statusNodeMap[type][status];
          data.image = info.icon;
          data.menuList = info.menuList;
          data.status = status;
          data.type = type;
        } else {
          type = data.infoData.type || quneeRefTypeMap[data.infoData.ref_type];
          status = 'init';
          info = $scope.statusNodeMap[type][status];

          if (info) {
            node.image = info.icon;
            node.menuList = info.menuList;
          };
        };
      };

      // 创建折线
      // from 起点
      // to终点
      // pathSegmentList 中间坐标
      var createEdge = function(graph, from, to, pathSegmentList) {
        var edge = graph.createEdge('edge', from, to);
        pathSegmentList && pathSegmentList.map(function(item) {
          edge.addPathSegment([item.x, item.y]);
        });
        return edge;
      };

      // 创建组节点
      var createGroup = function (groupData, expanded, graph) {
        var graph = graph || $window.editor.graph;
        expanded = expanded !== false;
        var group = graph.createGroup(groupData.name);
        group.expanded = expanded;
        var groupHandle = new Q.LabelUI(expanded ? "-" : "+");
        groupHandle.backgroundColor = "#2898E0";
        groupHandle.color = "#FFF";
        groupHandle.padding = new Q.Insets(0, 4);
        groupHandle.borderRadius = 0;
        groupHandle.position = Q.Position.RIGHT_TOP;
        groupHandle.anchorPosition = Q.Position.LEFT_TOP;
        groupHandle.type = "GroupHandle";
        groupHandle.reverseExpanded = function(evt){
            var g = this.parent.data;
            g.expanded = !g.expanded;
        }
        group.addUI(groupHandle, {
            property : "expanded",
            callback: function(value, ui){
              ui.data = value ? "-" : "+";
            }
        });
        return group;
      };

      // 解析json
      var translateToQuneeElements = function(json, graph){
          var map = {};
          var graph = graph || $window.editor.graph;

          // 创建普通节点
          if (json.nodes) {
              Q.forEach(json.nodes, function(data){
                  var node = graph.createNode(data.name, data.x || 0, data.y || 0, data.infoData.ref_type);
                  getNodeData(data, node);
                  node.set("data", data);
                  map[data.id] = node;
              });
          };

          // 创建组
          if (json.groups) {
              Q.forEach(json.groups, function(data){
                  var group = createGroup(data, true, graph);
                  getNodeData(data, group);
                  data.nodes.map(function(item){

                    // 子组
                    var innerNode = graph.createNode(item.name, item.x, item.y);
                    getNodeData(item, innerNode);
                    innerNode.set("data", item);
                    map[item.id] = innerNode;
                    group.addChild(innerNode);
                  });

                  group.set("data", data);
                  map[data.id] = group;
              });
          };

          // 创建连线
          if (json.edges) {
              Q.forEach(json.edges, function(data){
                  var from = map[data.from];
                  var to = map[data.to];

                  if(!from || !to){
                      return;
                  };

                  // data.pathSegmentList = [
                  //   {
                  //     x: 100,
                  //     y: 200
                  //   }
                  // ];

                  var edge = createEdge(graph, from, to, data.infoData.pathList);
                  edge.set("data", data);
              }, graph);
          };
      };


      // 显示右侧信息
      var onShowNodeInfo = function(evt) {
        var data = evt.getData();
        var nodeId;

        console.log(data)

        if(data && data._n0w.data){

          $timeout(function(){
            $scope.$broadcast('node_info',{
              nodeData : data._n0w.data
            })
          },100)

        }else{

          $timeout(function(){
            $scope.$broadcast('node_info',{
              nodeData : data.name
            })
          },100)

        };

        // 是否点击到空白处
        if (!!!data) {
          $scope.$apply(function() {
            $scope.processInfoState = false;
            $scope.nodeInfoState = false;
          });
        } else {

          if (data instanceof Q.Group) {
              var target = $window.editor.graph.hitTest(evt);

              if (target && target.type == "GroupHandle") {
                  target.reverseExpanded();
              } else {
                // nodeId = data._n0w.data.id;
                // $scope.nodeInfo = {
                //   id: nodeId
                // };

                $scope.$apply(function() {
                  $scope.processInfoState = false;
                  $scope.nodeInfoState = true;
                });
              }
          } else {
            // nodeId = data._n0w.data.id;
            // $scope.nodeInfo = {
            //   id: nodeId
            // };

            $scope.$apply(function() {
              $scope.processInfoState = false;
              $scope.nodeInfoState = true;
              //$scope.nodeInfoState = !!!$scope.nodeInfoState;
            });
          }
        };
      };

      var initQuneeEvent = function() {
        editor.graph.onclick = onShowNodeInfo;
      };

      // 获取加载完成的json
      var getChartJSON = function() {

        if (!!$window.editor) {
          return editor.graph.exportJSON(true, {space: '  '});
        } else {
          return null;
        };
      };

      var initEditor = function(callback) {
        $window.isEdit = true;
        $node.find('.editor').graphEditor({
          callback: function(editor){
            $('#search_input').css('margin-top','2px');
            $('.input-group').css('margin-top','2px')
            new GridBackground(editor.graph);
            // editor.graph.delayedRendering = true;
             if($scope.processId){
               translateToQuneeElements($scope.nodeList, editor.graph);
               editor.graph.moveToCenter();
               $timeout(function () {
                 editor.graph.zoomToOverview();
               }, 100);
             }

            $window.editor = editor;
            var selfJson = JSON.parse($scope.getChartJSON());
            initQuneeEvent();
            callback && callback();
          }
        });
      };

      // 局部刷新流程图
      var updateJSON = function(data) {
        editor.submitJSON(data);
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
        $window.$quneeNode = $node;
      };

      var bindListener = function() {
        $scope.nameInput = nameInput;
        $scope.classifyInput = classifyInput;
        //保存按钮
        $scope.processSave = processSave;
        //显示流程属性
        $scope.showProcessEdit = showProcessEdit;
        //放弃btn
        $scope.processAbandon =processAbandon;
        $scope.setTreeData = ManagerProcessTreeServ.setTreeData;
        //流程属性的内容
        $scope.getQuneeProcessInfo = getQuneeProcessInfo;
        //用户list
        $scope.getUserList = getUserList;
        $scope.createGroup = createGroup;
        //解析json
        $scope.translateToQuneeElements = translateToQuneeElements;
        //初始渲染图
        $scope.initEditor = initEditor;
        $scope.updateJSON = updateJSON;
        //获取加载完成的json
        $scope.getChartJSON = getChartJSON;
        //点击显示右侧的节点属性
        $scope.initQuneeEvent = initQuneeEvent;
        //$scope.getQuneeState = getQuneeState;
        //获取json
        $scope.getQuneeStateAndData = getQuneeStateAndData;
        $scope.giveUpBtn = giveUpBtn;
      };

      var initPlugins = function() {
        //初始化流程属性
        $scope.processInfo = {};
        $scope.nodeInfoState = false;
        $scope.processInfoState = false;
        $scope.nameInputShow = true;
        $scope.classifyInputShow = true;
        //流程属性的
        $scope.defaultText = "请选择...";
        $scope.changeNodeList = [];
        // 保存当前流程id
        processId = $stateParams.id;
        $scope.processId = processId;
        if(!!!$scope.processId){
          $scope.initEditor();
        }else{
          // 初始化socket链接
          //SocketServ.initSocket(processId);

          // 只监听跳转路由
          // $rootScope.$on('$stateChangeStart', function() {
          //
          //   // 如果状态不为终止 执行成功 的话 则清除执行id
          //   if ($scope.quneeState === 'manualQuit' || $scope.quneeState === 'execSuccess') {
          //     ParseMapServ.removeItem(processId, 'quitState');
          //     ParseMapServ.removeItem(processId, 'process');
          //   };
          // });
          // 用户接管表单参数
          $scope.userEditorTakeOverModel = {
            check: 1,
            resultQuery: true,
            remark: ''
          };

          // 所有节点状态字典
          ManagerProcessQuneeServ.getManagerProcessQuneeStateMap()
          .then(function(result) {
            console.log('所有节点状态字典',result)
            $scope.statusNodeMap = result;
            $window.statusNodeMap = result;
            getQuneeStateAndData();
          });
          $scope.getUserList();
          $scope.getQuneeProcessInfo();
          $node.find('.htrd-c-button-group').hide();
        }

        //分类tree的请求
        ManagerProcessTreeServ.getProcessTree()
        .then(function(result) {
          console.log('tree'+result)
          $scope.treeData = result.results.map($scope.setTreeData);
        });


        //接受分类tree的id
        $scope.$on('processEdit',function(evt,data) {
          $scope.processInfo.group_name = data.classify;
          console.log($scope.processInfo+"分类的tree")
        });

        //流程属性前置触发条件id
  	    $scope.$on('processProperty',function(evt,data) {
  	      $scope.processInfo.processSelect = data.processSelect.id;
  				console.log($scope.processInfo.processSelect+"前置触发条件idId")
  	    });

        //流程属性: 流程执行结果
        $scope.$on('processResult',function(evt,data) {
          $scope.processInfo.processResult = data.processResult;
          console.log($scope.processInfo)
        });

        //节点属性: 保存后隐藏
        $scope.$on('nodeShow',function(evt,data) {
          $scope.nodeInfoState = data.nodeInfoState;
          console.log($scope.nodeInfoState)
        });

      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {},
      'link': link,
      'templateUrl': 'view/directive/util/quneeEditorEdit.html'
  };
}]);

// 左侧菜单 -
angular.module('HTRD_AutoConsole.A').directive('quneeEditorHistoryList',['$state', function($state) {
  var link = function(s, e) {
      var $scope, $node;


      var activeItem = function(item) {
        console.log('processId', $scope.processId);
        console.log('execId', item.id);
        $state.go('console.base.manager.historyProcess', {
          id: item.id,
          processId: $scope.processId
        });
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.activeItem = activeItem;
      };

      var initPlugins = function() {
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'historyList': '=',
        'processId': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/quneeEditorHistoryList.html'
  };
}]);

// 左侧菜单 -
angular.module('HTRD_AutoConsole.A').directive('quneeEditorNodeEdit',['processEditServ','ManagerListServ',
function(processEditServ,ManagerListServ) {
  var link = function(s, e) {
      var $scope, $node;
      var nodeId ;

      //选择流程
      var activeProcess = function (item) {
        $scope.pipelineName = item.name;
  				$scope.quoteProcess = item;
          console.log($scope.quoteProcess)
  				// $scope.$emit("processProperty",{
  				// 	processSelect: item
  				// })
  		};

  		var getProcessListByName = function (item) {
  			ManagerListServ.getProcessList({
  							search: item
  			})
  				.then(function (ret) {

  						if (ret.status === 200) {
  								$scope.$broadcast('changeSelectFilterList', {
                    data: ret.results.data,
                    id: 'processSelectId'
                  });
  						} else {

  						}

  				});
  		};

      var machineCallback = function(item) {
        console.log('machineCallback', item.id);
      };

      var scriptCallback = function(item) {
        console.log('scriptCallback', item.id);
      };

      var resultCallback = function(item) {
        console.log('resultCallback', item);
      };

      var operationCallback = function(item) {
        console.log('operationCallback', item);
      };

      var saveNode = function(){
        $scope.nodeBaseInfo.id = nodeId;
        $scope.$emit('nodeShow',{
          nodeInfoState : false
        });
        //发请求$scope.nodeBaseInfo
        console.log('node的内容',$scope.nodeBaseInfo);
      }
      //机器
      var machineList = function(params){
        console.log(params);
        processEditServ.getMachineList(params)
        .then(function(result){
          $scope.machineData = result.results.map($scope.setTreeData);
        })
      };
      //脚本
      var scriptList = function(params){
        processEditServ.getScriptList(params)
        .then(function(result){
          $scope.scriptData = result.results.map($scope.setTreeData);
        })
      };
      //操作
      var operationList = function(params){
        processEditServ.getoperationList(params)
        .then(function(result){
          $scope.scriptData = result.results.map($scope.setTreeData);
        })
      };

      //用户
      var userList = function(params){
        processEditServ.getUserList(params)
        .then(function(result){
          $scope.userData = result.results.map($scope.setTreeData);
        })
      };

      //节点属性
      var nodeInfo = function(params){
        // processEditServ.getNodeInfo(params)
        // .then(function(result){
        //   console.log('nodeInfo');
        // })
        console.log('发送请求获取nodeInfo');
        $scope.machineSelected = '10.10.202.106';
        $scope.scriptSelected = '打开计算器';
        $scope.pipelineName = 'sssss';
        $scope.operationList = '';
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.resultCallback = resultCallback;
        $scope.saveNode = saveNode;
        //下拉菜单返回的id
        $scope.machineCallback = machineCallback;
        $scope.scriptCallback = scriptCallback;
        $scope.getProcessListByName = getProcessListByName;
        $scope.activeProcess = activeProcess;
        $scope.operationList = operationList;
      };

      var initPlugins = function() {
        $scope.nodeBaseInfo = {};
        $scope.userText = '请选择用户';
        $scope.processSelectId = 'processSelectId'
        $scope.$on('node_info',function(e,data){

          if(data.nodeData && data.nodeData.infoData){
            $scope.nodeInfo = data.nodeData.infoData.ref_type;
            $scope.nodeBaseInfo.type = data.nodeData.name;
            nodeId = data.nodeData.id;
            nodeInfo(nodeId);
          }else{
            $scope.nodeInfo = data.nodeData;
            $scope.nodeBaseInfo = {};
          };

          if(typeof($scope.nodeInfo) == 'string'){
            var nodeArr = ["节点","基本节点", "用户确认节点", "引用流程", "开始节点", "结束节点", "关机节点",  "重启节点"];
            $scope.nodeInfo = nodeArr.indexOf($scope.nodeInfo);
          };

          switch ($scope.nodeInfo) {
            case 1:
              $scope.nodeType = "任务脚本";
              $scope.machineShow = true;
              $scope.scriptShow = true;
              $scope.operationShow = true;
              $scope.nameShow = $scope.timeShow = $scope.processShow = false;
              //machineList(nodeId);
              //scriptList(nodeId);
            break;

            case 2:
              $scope.nodeType = "用户确认";
              $scope.nameShow = true;
              $scope.timeShow = true;
              $scope.operationShow = $scope.machineShow = $scope.scriptShow = $scope.processShow = false;
              //userList(nodeId);
              break;

            case 3:
              $scope.nodeType = "引用流程";
              $scope.processShow = true;
              $scope.timeShow = true;
              $scope.operationShow = $scope.nameShow = $scope.machineShow = $scope.scriptShow = false;
              //processList(nodeId);
              break;

            case 4:
              $scope.nodeType = "开始";
              $scope.operationShow = $scope.machineShow = $scope.processShow = $scope.timeShow = $scope.nameShow = $scope.scriptShow = false;
              break;

            case 5:
              $scope.nodeType = "结束";
              $scope.operationShow = $scope.machineShow = $scope.processShow = $scope.timeShow = $scope.nameShow = $scope.scriptShow = false;
              break;

              case 6:
                $scope.nodeType = "关机";
                $scope.machineShow = true;
                $scope.operationShow = $scope.processShow = $scope.timeShow = $scope.nameShow = $scope.scriptShow = false;
                //machineList(nodeId);
                break;

              case 7:
                $scope.nodeType = "重启";
                $scope.machineShow = true;
                $scope.operationShow = $scope.processShow = $scope.timeShow = $scope.nameShow = $scope.scriptShow = false;
                //machineList(nodeId);
                break;
            default:
          };
        });
        $scope.$on('nodeInfoList',function(e,data){
          switch (data.tag) {
            case 'process':
              $scope.nodeBaseInfo.process = data.quoteProcessSelect;
              break;
            default:
          }
          console.log('nodeInfoList',$scope.nodeBaseInfo)
        });
        //userlist的数据
        $scope.list = [
          {
            id: 01,
            title: 'chuxiaolin'
          },
          {
            id: 02,
            title: 'duoduohua'
          },
          {
            id: 03,
            title: 'wanglinin'
          },
          {
            id: 04,
            title: 'zhangllin'
          },
          {
            id: 05,
            title: 'langpinpin'
          }
        ];

        $scope.machineOptions = [
          {
            'id': 1,
            'title': '10.10.202.101'
          },
          {
            'id': 2,
            'title': '10.10.202.102'
          },
          {
            'id': 3,
            'title': '10.10.202.103'
          },
          {
            'id': 4,
            'title': '10.10.202.104'
          },
          {
            'id': 5,
            'title': '10.10.202.105'
          },
          {
            'id': 6,
            'title': '10.10.202.106'
          },
          {
            'id': 7,
            'title': '10.10.202.107'
          }
        ];

        $scope.scriptOptions = [
          {
            'id': 1,
            'title': '打开计算器'
          },
          {
            'id': 2,
            'title': '打开记事本'
          },
          {
            'id': 3,
            'title': '复制文件'
          },
          {
            'id': 4,
            'title': '关闭计算器'
          },
          {
            'id': 5,
            'title': '关闭记事本'
          },
          {
            'id': 6,
            'title': '下载文件'
          },
          {
            'id': 7,
            'title': '启win进程'
          },
          {
            'id': 8,
            'title': '切换杀进程'
          },
          {
            'id': 9,
            'title': '应急切换杀全进程'
          },
          {
            'id': 10,
            'title': '系统日志检查'
          }
        ];

        $scope.operationOptions = [
          {
            'id': 1,
            'title': '启动脚本'
          },
          {
            'id': 2,
            'title': '关闭脚本'
          },
          {
            'id': 3,
            'title': '重启脚本'
          }
        ];

        //user-menu返回的id
        $scope.$on('userList',function(e,data){
          console.log(data,nodeId);
          $scope.nodeBaseInfo.userIds = data.userIds;
        })

        $scope.$on('timeOut',function(e,data){
          console.log('time_out',data)
        })
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'nodeInfo': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/quneeEditorNodeEdit.html'
  };
}]);

// 左侧菜单 -
angular.module('HTRD_AutoConsole.A').directive('quneeEditorNodeInfo',['ManagerProcessServ',
function(ManagerProcessServ) {
  var link = function(s, e) {
      var $scope, $node;

      var quneeRefTypeMapStr = {
        1: '基本节点',
        2: '用户确认节点',
        3: '引用流程节点',
        4: '开始节点',
        5: '结束节点',
        6: '关机节点',
        7: '重启节点'
      };

      var getNodeCharts = function() {
        getNodeChartByCPU();
        getNodeChartByMemory();
      };

      var getNodeChartByCPU = function() {
        ManagerProcessServ.getNodeChartByCPU()
        .then(function(ret) {

          if (ret.state === 0) {
            $scope.chartDataByCPU = {
              xAxis: [],
              series: []
            };

            // 格式化数据
            ret.data.map(function(item, index) {
              var xAxiItem = new Date(parseInt(item.clock * 1000)).toTimeString().split(' ')[0];
              var serieItem = item.value;
              $scope.chartDataByCPU.xAxis.push(xAxiItem);
              $scope.chartDataByCPU.series.push(serieItem);
            });

            $scope.chartDataByCPU.title = ['CPU'];
          };
        });
      };

      var getNodeChartByMemory = function() {
        ManagerProcessServ.getNodeChartByMemory()
        .then(function(ret) {

          if (ret.state === 0) {
            $scope.chartDataByMemory= {
              xAxis: [],
              series: []
            };

            // 格式化数据
            ret.data.map(function(item, index) {
              var xAxiItem = new Date(parseInt(item.clock * 1000)).toTimeString().split(' ')[0];
              var serieItem = item.value;
              $scope.chartDataByMemory.xAxis.push(xAxiItem);
              $scope.chartDataByMemory.series.push(serieItem);
            });

            $scope.chartDataByMemory.title = ['内存'];
          };
        });
      };

      var getNodeInfo = function() {
        ManagerProcessServ.getNodeInfo({
          id: $scope.nodeInfo.id
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.nodeBaseInfo = ret.results;
            $scope.nodeBaseInfo.type = quneeRefTypeMapStr[$scope.nodeBaseInfo.ref_type];
          } else {
            $scope.nodeBaseInfo = {};
          };
        });
      };

      var callback = function(index) {
        $scope.activeIndex = index;
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.callback = callback;
      };

      var initPlugins = function() {
        $scope.activeIndex = 1;
        $scope.$watch('nodeInfo', function(a, b) {

          // nodeId change 后 加载多个图表 和 基本信息
          getNodeInfo();
          getNodeCharts();
        });
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'nodeInfo': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/quneeEditorNodeInfo.html'
  };
}]);

// 流程属性编辑
angular.module('HTRD_AutoConsole.A').directive('quneeEditorProcessEdit',['ManagerListServ',function(ManagerListServ) {
	var link = function(s, e) {
		var $scope, $node;

		//选择流程
		var activeProcess = function (item) {
			$scope.pipelineName = item.name;
				console.log('aaaaa')
				$scope.$emit("processProperty",{
					processSelect: item
				})
		};

		var getProcessListName = function (item) {
			ManagerListServ.getProcessList({
				search: item
			})
			.then(function (ret) {

				if (ret.status === 200) {
					$scope.$broadcast('changeSelectFilterList', {
						data: ret.results.data,
						id: 'processSelectId'
					});
				};
			});
		};

		var parseDOM = function() {
			$scope = s;
			$node = $(e[0]);
		};

		var bindListener = function() {
			$scope.activeProcess = activeProcess;
			$scope.getProcessListName = getProcessListName;
		};


		var initPlugins = function() {
			$scope.processResultText = '请选择流程执行结果';
			$scope.processSelectId = 'processSelectId'
			$scope.processResultList = [
				{
					id: 1,
					title: '执行成功'
				},

				{
					id: 2,
					title: '执行失败'
				}
			];

		};

		var init = function() {
			parseDOM();
			bindListener();
			initPlugins();
		};

		init();
	};

	return {
		'replace': true,
		'restrict' : 'AEC',
		'scope': {
			'processInfo':'=',
			'treeData':'=',
		},
		'link': link,
		'templateUrl': 'view/directive/util/quneeEditorProcessEdit.html'
	};
}]);

// 左侧菜单 -
angular.module('HTRD_AutoConsole.A').directive('quneeEditorProcessInfo',[function() {
  var link = function(s, e) {
      var $scope, $node;

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {};

      var initPlugins = function() {};

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'processInfo': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/quneeEditorProcessInfo.html'
  };
}]);

// 拓扑图预览
angular.module('HTRD_AutoConsole.A').directive('quneeInfoHistory',['$window', '$timeout', '$interval', '$stateParams', '$rootScope', 'ManagerProcessQuneeServ', 'DialogServ', 'SocketServ', 'AlertServ', 'ParseMapServ', 'DateParseServ',
function($window, $timeout, $interval, $stateParams, $rootScope, ManagerProcessQuneeServ, DialogServ, SocketServ, AlertServ, ParseMapServ, DateParseServ) {
  var link = function(s, e) {
      var $scope, $node, testCount = 0;
      var quneeStart, strapModal;

      // 流程id
      var processId = 0;

      var execId = 0;

      // 执行id
      var execId;

      var nodeStatusMap = {
        // -1: 'st_unknow',  # 未知状态

        // 流程初始化
        0: 'init'
        ,
        // # 正在检测
        1: 'check',

        // # 流程检测错误
        2: 'checkError',

        // # 节点检测－脚本错误
        3: 'checkScriptError',

        // # 节点检测－主机错误
        4: 'checkError',

        // # 检测成功
        5: 'checkSuccess',

        // # 正在执行
        6: 'running',

        // # 执行错误
        7: 'runError',

        // # 执行超时
        8: 'runTimeout',

        // # 执行成功
        9: 'runSuccess',

        // # 等待用户确认
        10: 'waitUserConfirm',

        // # 停止执行
        11: 'quit',

        // # 正在停止
        12: 'st_stopping',

        // # 暂停执行
        13: 'pause',

        // # 正在暂停
        14: 'st_pausing',

        // # 等待用户输入
        15: 'st_waiting_for_input',

        // # 执行单个节点/重做
        16: 'st_running_one',

        // # 执行单个节点/重做 成功
        17: 'st_run_one_ok',

        // # 执行单个节点/重做 失败
        18: 'st_run_one_err',

        // # 用户拒绝
        19: 'st_confirm_refused',

        // 执行完成但有错误
        20: 'runSuccessAndNodeError',

        // 手工接管后的执行结果：成功
        21: 'takeOverSucc',

        // 手工接管后的执行结果：失败
        22: 'takeOverError'
      };

      // 如果状态为数字 则转换
      var quneeStateMap = {
        0: 'init', // 默认(1级分类)
        1: 'check', // 检测中(1级分类)
        2: 'exec', // 执行中(1级分类)
        3: 'checkError', // 检测异常(2级分类)
        4: 'checkSuccess', // 检测成功(2级分类)
        5: 'execSuccess' // 执行成功
      };

      // 执行中状态
      var runningMap = {
        0: 'pause',
        1: 'running'
      };

      // 执行中节点状态
      var runningNodeMap = {
        0: 'error',
        1: 'overtime',
        2: 'runningSuccess'
      };

      var quneeRefTypeMap = {
        1: 'basicNode',
        2: 'userConfirmNode',
        3: 'groupNode',
        4: 'startNode',
        5: 'endNode',
        6: 'closeNode',
        7: 'restartNode'
      };

      // 转换json字符串 , 组装完整的json数据
      // var quneeParseNodeJSON = function(nodeList, nodeStatusList) {
      //   var nodeJSON;
      //
      //   if (typeof nodeList === 'string') {
      //     nodeJSON = JSON.parse(nodeList);
      //   } else {
      //     nodeJSON = nodeList;
      //   };
      //
      //   // 判断节点状态列表内是否有数据 没有则代表初始化状态
      //   if (!!nodeStatusList) {
      //     nodeStatusList.map(function(item) {
      //
      //       for (var key in nodeJSON) {
      //         nodeJSON[key].map(function(node) {
      //
      //           if (node.id === item.node_id) {
      //             node.infoData.status = nodeStatusMap[item.status] || 'init';
      //           } else {
      //             node.infoData.status = 'init';
      //           };
      //
      //           node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
      //         });
      //       };
      //     });
      //   } else {
      //
      //     for (var key in nodeJSON) {
      //       nodeJSON[key].map(function(node) {
      //         node.infoData.status = 'init';
      //         node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
      //       });
      //     };
      //   };
      //   return nodeJSON;
      // };

      var quneeParseNodeJSON = function(nodeList, nodeStatusList) {
        var nodeJSON;

        if (typeof nodeList === 'string') {
          nodeJSON = JSON.parse(nodeList);
        } else {
          nodeJSON = nodeList;
        };

        console.log('quneeParseNodeJSON');
        console.log(nodeJSON);
        console.log(nodeStatusList);

        // 判断节点状态列表内是否有数据 没有则代表初始化状态
        if (!!nodeStatusList) {

          for (var key in nodeJSON) {

            if (key === 'groups') {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(group) {

                  // 循环组内的节点状态
                  group.nodes.map(function(node) {

                    if (node.id === (item.node_id || item.id)) {
                      node.infoData.status = nodeStatusMap[item.status] || 'init';
                    };

                    node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                  });
                });
              });
            } else {
              nodeStatusList.map(function(item) {
                nodeJSON[key].map(function(node) {

                  if (node.id === (item.node_id || item.id)) {
                    node.infoData.status = nodeStatusMap[item.status] || 'init';
                  };

                  node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
                });
              });
            }
          };
        } else {

          for (var key in nodeJSON) {
            nodeJSON[key].map(function(node) {
              node.infoData.status = 'init';
              node.infoData.type = quneeRefTypeMap[node.infoData.ref_type];
            });
          };
        };
        return nodeJSON;
      };

      var resetNodes = function() {
        var refId;
        $scope.nodeList = quneeParseNodeJSON($scope.pipeline);

        // 先获取全部node
        selfJson = JSON.parse($scope.getChartJSON());
        selfJson.datas.map(function(selfItem, index) {

          // 更新普通节点
          if (selfItem._className === 'Q.Node') {

            if (!!!selfItem.json.properties.data.id) {
              refId = selfItem.json.properties.data.$ref;
              selfItem.json.properties.data = selfJson.refs[refId];
            };

            selfItem.json.properties.data.infoData.status = 'init';
            getNodeData(selfItem.json.properties.data, selfItem.json);
          };
        });

        updateJSON(selfJson);
      };

      var updateQuneeStateBtn = function() {
        $node.find('.htrd-c-button-group').eq(0).hide();
      };

      var socketPullData = function(data) {
        $node.trigger('qunee.stateChange', data);
      };

      var getQuneeNodeInfo = function(data) {
        $scope.$apply(function () {
          $scope.historyListState = false;
          $scope.processInfoState = false;
          $scope.nodeInfoState = true;
        });
      };

      var getQuneeProcessInfo = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeInfo({
          id: processId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.processInfo = ret.results;
          } else {

          };
        });
      };

      var getQuneeHistoryList = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeHistoryList({
          id: processId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.historyList = ret.results;
          } else {
            $scope.historyList = [];
            AlertServ.showError(ret.msg);
          };
        });
      };

      var getUserList = function() {
        ManagerProcessQuneeServ.getUserList()
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.userList = [];
            ret.results.data.map(function(item, index) {
              $scope.userList.push({
                id: item.id,
                title: item.username
              });
            });
          }
        });
      };

      var activeUser = function(item) {
        $scope.userConfirmModel.userId = item.id;
      };

      // 用户用户确认/重做弹框
      var submitUserConfirm = function() {

        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.submotManagerProcessQuneeUserConfirm($scope.userConfirmModel)
        .then(function(ret) {

          if (ret.status === 200) {
            AlertServ.showSuccess(ret.msg);
            strapModal.hide();
            $scope.userConfirmModel = {
              errerMsg: '提示：用户确认超时2分钟。'
            };
            $scope.selectDefaultText = '请选择用户';
            $scope.quneeState = 'running';
            $timeout(function() {
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
            }, 2000);
          } else {
            $scope.userConfirmModel.errerMsg = ret.msg || '密码错误, 请重试';
            // AlertServ.showError();
          };
        });
      };

      // 用户接管
      var submitEditorTakeOver = function() {

        var data = {
          // id: $scope.userEditorTakeOverModel.id,
          id: execId,
          result_status: $scope.userEditorTakeOverModel.check,
          result_info: $scope.userEditorTakeOverModel.remark.trim()
        };
        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.ManagerProcessQuneeManualNozzleNode(data)
        .then(function(ret) {

          if (ret.status === 200) {
            AlertServ.showSuccess(ret.msg);
            strapModal.hide();
            $scope.userEditorTakeOverModel = {};
            $scope.quneeState = 'manualQuit';
            updateQuneeStateBtn();

            if (!$node.find('.qunee-start').is(":hidden")) {
              ParseMapServ.setItem(processId, 'start', 'quitState');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              ParseMapServ.setItem(processId, 'continue', 'quitState');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              ParseMapServ.setItem(processId, 'pause', 'quitState');
            };

            $timeout(function() {
              $scope.socketPullData('quit');
            }, 2000);
          } else {
            AlertServ.showError(ret.msg);
          }
        });
      };

      // 手动终止确认
      var submitProcessQuit = function() {
        $scope.socketPullData('requesting');
        ManagerProcessQuneeServ.ManagerProcessQuneeQuit({
          id: execId,
          result_info: $scope.userEditorQuitModel.remark
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.userEditorQuitModel = {};
            strapModal.hide();
            $timeout.cancel(quneeStart);
            $scope.quneeState = 'manualQuit';

            if (!$node.find('.qunee-start').is(":hidden")) {
              ParseMapServ.setItem(processId, 'start', 'quitState');
            };

            if (!$node.find('.qunee-continue').is(":hidden")) {
              ParseMapServ.setItem(processId, 'continue', 'quitState');
            };

            if (!$node.find('.qunee-pause').is(":hidden")) {
              ParseMapServ.setItem(processId, 'pause', 'quitState');
            };

            updateQuneeStateBtn();
            AlertServ.showSuccess(ret.msg);
            $timeout(function() {
              $scope.socketPullData('quit');
            }, 2000);
          } else {
            AlertServ.showError(ret.msg);
          };
        });
      };

      var getManagerProcessQuneeLogList = function(processId) {
        console.log('execId',execId)
        ManagerProcessQuneeServ.getManagerProcessQuneeLogList({
          // id: 100
          id: execId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            $scope.logList = ret.results;
            $scope.logList.map(function(item, index) {
              item.created_at = DateParseServ.dateParse(item.created_at);
            });
            // AlertServ.showSuccess(ret.msg);
          } else {
            AlertServ.showError(ret.msg);
          };
        });
      };

      // 获取当前流程节点json数据以及状态
      var getQuneeStateAndData = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeStateAndData({
          id: processId
        })
        .then(function(ret) {
          var quneeState;

          console.log('历史执行');

          if (ret.status === 200) {

            // 获取1级状态 0 基本 1 检测中 2 执行中
            quneeState = ret.results.status;

            // 只可能是执行完的策略才能进
            // if (quneeState === 0) {

            if (!!ret.results.checked) {
              $scope.init = true;
              $scope.lastCheckDateStr = '上次检测时间: ' + ret.results.checked.ended_at.replace('T', ' ').replace('Z','');
              $scope.lastCheckStatus = ret.results.checked.status;
              $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline);
              // $scope.initEditor();

              if (typeof ret.results.checked.status === 'number') {
                $scope.quneeState = quneeStateMap[ret.results.checked.status];
              } else {
                $scope.quneeState = ret.results.checked.status || 'init';
              };

              // 获取执行的状态
              $scope.getQuneeExecState($scope.nodeList);
            } else {
              $scope.nodeList = quneeParseNodeJSON(ret.results.pipeline);
              $scope.initEditor();
              $scope.quneeState = 'init';
            };
            updateQuneeStateBtn();
            // }
          };
        });
      };

      // 获取执行的具体状态
      var getQuneeExecState = function(pipeline) {
        ManagerProcessQuneeServ.getManagerProcessQuneeExecState({
          id: execId
        })
        .then(function(ret) {

          if (ret.status === 200) {
            console.log('ret.results', ret.results);
            console.log('最后执行状态 ret.results.result_status', ret.results.result_status);
            var statusStr = nodeStatusMap[ret.results.result_status];

            if (ret.results.exec_nodes) {
              $scope.nodeList = quneeParseNodeJSON(pipeline, ret.results.exec_nodes);
            } else {
              $scope.nodeList = [];
            };

            console.log('$scope.nodeList', $scope.nodeList);

            $scope.initEditor(function() {
              console.log('statusStr', statusStr);
              $scope.socketPullData(statusStr);
              $node.find('.qunee-history').hide();
            });

            updateQuneeStateBtn();
            // resetNodes();
          }
        });
      };

      // 获取流程节点
      var getQuneeState = function() {
        ManagerProcessQuneeServ.getManagerProcessQuneeState()
        .then(function(result) {

          if (result.status === 200) {
            $scope.quneeState = result.results.state;
            updateQuneeStateBtn();
          };
        });
      };

      var onStateChange = function(evt, data) {
        console.log('$scope.quneeState', data);

        // 所有标识状态的集合
        // 所有标识状态的集合
        var tagStatusMap = {
          requesting: {
            status: 'qunee-status label label-info bg-blue',
            text: '正在请求中'
          },

          check: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程检测中'
          },

          checkSuccess: {
            status: 'qunee-status label label-success bg-green',
            text: '检测成功'
          },

          checkError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          running: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程执行中'
          },

          runError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          pause: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程已暂停'
          },

          parseError: {
            status: 'qunee-status label label-danger',
            text: '检测异常'
          },

          st_pausing: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程已暂停'
          },

          continue: {
            status: 'qunee-status label label-info bg-blue',
            text: '流程执行中'
          },

          quit: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止'
          },

          manualQuit: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止'
          },

          st_stopping: {
            status: 'qunee-status label label-danger',
            text: '流程被手工终止'
          },

          runSuccess: {
            status: 'qunee-status label label-success bg-green',
            text: '流程执行成功'
          },

          runSuccessAndNodeError: {
            status: 'qunee-status label label-danger',
            text: '流程执行成功但节点有错误'
          },

          noApproval: {
            status: 'qunee-status label label-danger',
            text: '不认可'
          },

          takeOverSucc: {
            status: 'qunee-status label label-success bg-green',
            text: '手工接管后的执行结果：成功'
          },

          takeOverError: {
            status: 'qunee-status label label-danger',
            text: '手工接管后的执行结果：失败'
          },

          waitUserConfirm: {
            status: 'qunee-status label label-info bg-blue',
            text: '等待用户确认'
          },

          st_confirm_refused: {
            status: 'qunee-status label label-danger',
            text: '被不认可终止'
          },

          // 执行完成但有错误
          runSuccessAndNodeError: {
            status: 'qunee-status label label-danger',
            text: '执行完成但有错误'
          },

          takeOverSucc: {
            status: 'qunee-status label label-success bg-green',
            text: '手工接管后的执行结果：成功'
          },

          takeOverError: {
            status: 'qunee-status label label-danger',
            text: '手工接管后的执行结果：失败'
          }
        };

        if (!!tagStatusMap[data]) {
          var status = tagStatusMap[data].status;
          var text = tagStatusMap[data].text;
          $node.find('.qunee-status').removeClass().addClass(status);
          $node.find('.qunee-status').text(text);
        };
      };

      var onPushNodeData = function(data) {
        $scope.logList = $scope.logList || [];
        // $scope.logList.push(data.log);
        data.log.created_at = DateParseServ.dateParse(data.log.created_at);
        $scope.logList.push(data.log);
        console.log(data);
        var selfJson = JSON.parse($scope.getChartJSON());

        // 保存组内节点
        var groupNodes = [];
        selfJson.datas.map(function(selfItem, index) {

          if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
            groupNodes.push({
              index: index,
              item: selfItem,
              ref: selfItem.json.properties.data.$ref
            });
          };
        });

        // 更新节点数据 只会改变单个节点
        selfJson.datas.map(function(selfItem, index) {

          // 更新普通节点
          if (selfItem._className === 'Q.Node') {

            if (!!selfItem.json.properties.data.id) {

              if (selfItem.json.properties.data.id === data.node.id) {
                selfItem.json.properties.data.infoData.status = data.node.status;
                updateNode = selfItem.json.properties.data;
                getNodeData(selfItem.json.properties.data, selfItem.json);
                $scope.isShowDialog = (data.node.status === 'running' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');

                if ($scope.isShowDialog) {
                  $scope.quneeState = 'waitConfirmOrSubmit';
                  $scope.socketPullData('pause');
                };
              };
            };
          };
        });

        updateJSON(selfJson);

        if ($scope.isShowDialog) {
          $scope.userConfirmModel.id = updateNode.id;
          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
        updateQuneeStateBtn();



      };

      var onQuneeInfo = function(evt, data) {
        $scope.$apply(function() {
          $scope.processInfoState = true;
          $scope.historyListState = false;
          $scope.nodeInfoState = false;
        });
      };

      var onQuneeHistory = function(evt, data) {
        $scope.$apply(function() {
          $scope.historyListState = true;
          $scope.processInfoState = false;
          $scope.nodeInfoState = false;
        });
      };

      // 检测
      var onQuneeCheck = function(evt, data) {

        if ($scope.stateConfig.check) {
          $scope.quneeState = 'check';

          // 改变流程摁键组的状态
          updateQuneeStateBtn();

          // 改变流程状态标示的状态
          $scope.socketPullData('requesting');
          ManagerProcessQuneeServ.ManagerProcessQuneeCheck({
            id: processId
          })
          .then(function(ret) {
            $timeout(function () {

              if (ret.status === 200) {
                $scope.quneeState = 'checkSuccess';
              } else {
                $scope.quneeState = 'checkError';
              };

              // 改变流程状态标示的状态
              $scope.socketPullData($scope.quneeState);
              updateQuneeStateBtn();
            }, 2000);
          });

        };
      };

      // 点击执行
      var onQuneeStart = function(evt, data) {

        if ($scope.stateConfig.start) {

          // 改变流程状态标示的状态
          $scope.socketPullData('requesting');
          $node.find('.qunee-start').addClass('default btn-outline');
          $timeout(function() {
            ManagerProcessQuneeServ.ManagerProcessQuneeStart({
              id: processId
            })
            .then(function(ret) {

              if (ret.status === 200) {
                var updateNode;
                $node.find('.qunee-start').removeClass('default btn-outline');
                ParseMapServ.setItem(processId, ret.results.pl_ex_id, 'process');
                execId = ParseMapServ.getItem(processId, 'process')
                // AlertServ.showSuccess(ret.msg);
                $scope.stateConfig.start = !!!$scope.stateConfig.start;
                $scope.quneeState = 'running';

                // 改变流程状态标示的状态
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();

                // // 模拟socket推送的节点状态
                // quneeStart = $timeout(function() {
                //
                //   // socket更新的数据
                //   var socketData = {
                //
                //     // 改变的节点属性 (普通节点 , 组节点)
                //     // changeNodeList: {
                //     //   nodes: {
                //     //     id: 7,
                //     //     status: "running"
                //     //   }
                //     // },
                //
                //     changeNodeList: {
                //       nodes: {
                //         id: 3,
                //         status: "error"
                //       }
                //     },
                //
                //     // 流程状态
                //     status: 'userConfirmNode',
                //
                //     // 单条日志
                //     log: {}
                //   }
                //
                //   var selfJson = JSON.parse($scope.getChartJSON());
                //
                //   // 保存组内节点
                //   var groupNodes = [];
                //   selfJson.datas.map(function(selfItem, index) {
                //
                //     if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
                //       groupNodes.push({
                //         index: index,
                //         item: selfItem,
                //         ref: selfItem.json.properties.data.$ref
                //       });
                //     };
                //   });
                //
                //   // 更新节点数据 只会改变单个节点
                //   selfJson.datas.map(function(selfItem, index) {
                //
                //     // 更新普通节点
                //     if (selfItem._className === 'Q.Node') {
                //
                //       if (!!selfItem.json.properties.data.id) {
                //
                //         if (selfItem.json.properties.data.id === data.node.id) {
                //           selfItem.json.properties.data.infoData.status = data.node.status;
                //           updateNode = selfItem.json.properties.data;
                //           getNodeData(selfItem.json.properties.data, selfItem.json);
                //           $scope.isShowDialog = (data.node.status === 'running' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');
                //
                //           if ($scope.isShowDialog) {
                //             $scope.quneeState = 'waitConfirmOrSubmit';
                //             $scope.socketPullData('pause');
                //           };
                //         };
                //       };
                //     };
                //   });
                //
                //   updateJSON(selfJson);
                //
                //   if ($scope.isShowDialog) {
                //     $scope.userConfirmModel.id = updateNode.id;
                //     strapModal = DialogServ.modal({
                //       'scope': $scope,
                //       'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
                //     });
                //     strapModal.$promise.then(strapModal.show);
                //   };
                //   updateQuneeStateBtn();
                // }, 2000);
              } else {
                AlertServ.showError(ret.msg);
              };
            });
          }, 2000);
        };
      };

      // 暂停
      var onQuneePause = function(evt, data) {

        if ($scope.stateConfig.pause) {
          $scope.socketPullData('requesting');
          $node.find('.qunee-pause').addClass('default btn-outline');

          ManagerProcessQuneeServ.ManagerProcessQuneePause({
            id: execId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              $timeout(function() {
                $node.find('.qunee-pause').removeClass('default btn-outline');
                $scope.quneeState = 'pause';
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();
                AlertServ.showSuccess(ret.msg);
              }, 2000);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 继续
      var onQuneeContinue = function(evt, data) {

        if ($scope.stateConfig.continue) {
          var updateNode;
          $scope.socketPullData('requesting');
          $node.find('.qunee-continue').addClass('default btn-outline');
          ManagerProcessQuneeServ.ManagerProcessQuneeContinue({
            id: execId
          })
          .then(function(ret) {

            if (ret.status === 200) {
              $scope.quneeState = 'running';
              $timeout(function() {
                $node.find('.qunee-continue').removeClass('default btn-outline');
                $scope.socketPullData($scope.quneeState);
                updateQuneeStateBtn();
              }, 2000);

              // // 模拟socket推送的节点状态
              // quneeStart = $timeout(function() {
              //
              //   // socket更新的数据
              //   var socketData = {
              //
              //     // 改变的节点属性 (普通节点 , 组节点)
              //     changeNodeList: {
              //       nodes: {
              //         id: 7,
              //         status: "running"
              //       }
              //     },
              //
              //     // 流程状态
              //     status: 'userConfirmNode',
              //
              //     // 单条日志
              //     log: {}
              //   }
              //
              //   var selfJson = JSON.parse($scope.getChartJSON());
              //
              //   // 保存组内节点
              //   var groupNodes = [];
              //   selfJson.datas.map(function(selfItem, index) {
              //
              //     if (selfItem._className === 'Q.Node' && !!selfItem.json.properties.data.$ref) {
              //       groupNodes.push({
              //         index: index,
              //         item: selfItem,
              //         ref: selfItem.json.properties.data.$ref
              //       });
              //     };
              //   });
              //
              //   // 更新节点数据 只会改变单个节点
              //   selfJson.datas.map(function(selfItem, index) {
              //
              //     // 更新普通节点
              //     if (selfItem._className === 'Q.Node') {
              //
              //       if (!!selfItem.json.properties.data.id) {
              //
              //         if (selfItem.json.properties.data.id === data.node.id) {
              //           selfItem.json.properties.data.infoData.status = data.node.status;
              //           updateNode = selfItem.json.properties.data;
              //           getNodeData(selfItem.json.properties.data, selfItem.json);
              //           $scope.isShowDialog = (data.node.status === 'running' && selfItem.json.properties.data.infoData.type === 'userConfirmNode');
              //
              //           if ($scope.isShowDialog) {
              //             $scope.quneeState = 'waitConfirmOrSubmit';
              //             $scope.socketPullData('pause');
              //           };
              //         };
              //       };
              //     };
              //   });
              //
              //   updateJSON(selfJson);
              //
              //   if ($scope.isShowDialog) {
              //     $scope.userConfirmModel.id = updateNode.id;
              //     strapModal = DialogServ.modal({
              //       'scope': $scope,
              //       'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
              //     });
              //     strapModal.$promise.then(strapModal.show);
              //   };
              //   updateQuneeStateBtn();
              // }, 4000);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        };
      };

      // 终止
      var onQuneeQuit = function(evt, data) {

        if ($scope.stateConfig.quit) {

          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorQuit.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
      };

      // 跳过本节点
      var onQuneeSkipSelfNode = function(evt, data) {

        if (!!!data.disabled) {
          ManagerProcessQuneeServ.ManagerProcessQuneeSkipSelfNode()
          .then(function(ret) {
            console.log(ret);
          });
        };
      };

      // 重做本节点
      var onQuneeRestartSelfNode = function(evt, data) {
        $scope.isShowDialog = (!!(data.type === 'userConfirmNode' && data.status === 'running'));

        if ($scope.isShowDialog) {
          $scope.userConfirmModel.id = data.id;
          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorWaitConfirmOrSubmit.html'
          });
          strapModal.$promise.then(strapModal.show);
        } else {
          ManagerProcessQuneeServ.ManagerProcessQuneeResetNode({
            id: execId,
            node_id: data.id
          })
          .then(function(ret) {

            if (ret.status === 200) {
              AlertServ.showSuccess(ret.msg);
            } else {
              AlertServ.showError(ret.msg);
            };
          });
        }
        $scope.quneeState = 'waitConfirmOrSubmit';
        $scope.socketPullData('pause');
        updateQuneeStateBtn();
      };

      // 手工接管
      var onQuneeManualNozzleNode = function(evt, data) {

        if (!!!data.disabled) {
          $scope.userEditorTakeOverModel.id = data.id;
          strapModal = DialogServ.modal({
            'scope': $scope,
            'templateUrl': 'view/console/modal/quneeEditorTakeOver.html'
          });
          strapModal.$promise.then(strapModal.show);
        };
      };

      // 切换日志显示状态
      var toggleLog = function() {
        $scope.logShowState = !!!$scope.logShowState;
      };

      var getNodeData = function(data, node, isGroup) {
        var type, status, info;

        if (isGroup) {
          type = quneeRefTypeMap[data.infoData.ref_type];

          if (node.status && typeof node.status === 'string') {
            status = node.infoData.status;
          } else {
            status = nodeStatusMap[node.status] || 'init';
          };
          info = $scope.statusNodeMap[type][status];
          data.image = info.icon;
          data.menuList = info.menuList;
          data.status = status;
          data.type = type;
        } else {
          type = data.infoData.type || quneeRefTypeMap[data.infoData.ref_type];

          if (data.infoData.status && typeof data.infoData.status === 'string') {
            status = data.infoData.status;
          } else {
            status = nodeStatusMap[data.infoData.status] || 'init';
          };
          info = $scope.statusNodeMap[type][status];

          if (info) {
            node.image = info.icon;
            node.menuList = info.menuList;
          };
        };

        console.log('info', info);
      };

      // 创建直线
      var createEdge = function(graph, from, to, pathSegmentList) {
        var edge = graph.createEdge('edge', from, to);
        pathSegmentList && pathSegmentList.map(function(item) {
          edge.addPathSegment([item.x, item.y]);
        });
        return edge;
      };


      // 创建组节点
      var createGroup = function (groupData, expanded, graph) {
        var graph = graph || $window.editor.graph;
        expanded = expanded !== false;
        var group = graph.createGroup(groupData.name);

        group.expanded = expanded;
        var groupHandle = new Q.LabelUI(expanded ? "-" : "+");
        groupHandle.backgroundColor = "#2898E0";
        groupHandle.color = "#FFF";
        groupHandle.padding = new Q.Insets(0, 4);
        groupHandle.borderRadius = 0;
        groupHandle.position = Q.Position.RIGHT_TOP;
        groupHandle.anchorPosition = Q.Position.LEFT_TOP;
        groupHandle.type = "GroupHandle";
        groupHandle.reverseExpanded = function(evt){
            var g = this.parent.data;
            g.expanded = !g.expanded;
        }
        group.addUI(groupHandle, {
            property : "expanded",
            callback: function(value, ui){
                ui.data = value ? "-" : "+";
            }
        });
        return group;
      };

      // 解析json
      var translateToQuneeElements = function(json, graph){
          var map = {};
          var graph = graph || $window.editor.graph;

          // 创建普通节点
          if (json.nodes) {
              Q.forEach(json.nodes, function(data){
                  var node = graph.createNode(data.name, data.x || 0, data.y || 0);
                  getNodeData(data, node);
                  node.set("data", data);
                  map[data.id] = node;
              });
          };

          // 创建组
          if (json.groups) {
              Q.forEach(json.groups, function(data){
                  var group = createGroup(data, true, graph);
                  getNodeData(data, group);
                  data.nodes.map(function(item){

                    // 子组
                    var innerNode = graph.createNode(item.name, item.x, item.y);
                    getNodeData(item, innerNode);
                    innerNode.set("data", item);
                    map[item.id] = innerNode;
                    group.addChild(innerNode);
                  });

                  group.set("data", data);
                  map[data.id] = group;
              });
          };

          // 创建连线
          if (json.edges) {
              Q.forEach(json.edges, function(data){
                  var from = map[data.from];
                  var to = map[data.to];

                  if(!from || !to){
                      return;
                  };

                  // data.pathSegmentList = [
                  //   {
                  //     x: 100,
                  //     y: 200
                  //   }
                  // ];

                  var edge = createEdge(graph, from, to, data.infoData.pathList);
                  edge.set("data", data);
              }, graph);
          };
      };

      // 显示右侧信息
      var onShowNodeInfo = function(evt) {

        var data = evt.getData();

        // 是否点击到空白处
        if (!!!data) {
          $scope.$apply(function() {
            $scope.historyListState = false;
            $scope.processInfoState = false;
            $scope.nodeInfoState = false;
          });
          return false;
        } else {
          console.log('getQuneeNodeInfo');
          // $scope.getQuneeNodeInfo(data);
        };

        if (data instanceof Q.Group) {
            var target = $window.editor.graph.hitTest(evt);

            if (target && target.type == "GroupHandle") {
                target.reverseExpanded();
            };
        };
      };

      var initQuneeEvent = function() {
        editor.graph.onclick = onShowNodeInfo;
      };

      // 获取加载完成的json
      var getChartJSON = function() {
        return editor.graph.exportJSON(true, {space: '  '});
      };

      var initEditor = function(callback) {
        $node.find('.editor').graphEditor({
          callback: function(editor){
            translateToQuneeElements($scope.nodeList, editor.graph);
            editor.graph.moveToCenter();
            editor.graph.zoomToOverview();
            $window.editor = editor;
            var selfJson = JSON.parse($scope.getChartJSON());
            console.log('selfJson', selfJson);
            initQuneeEvent();
            callback && callback();
          }
        });
      };

      // 局部刷新流程图
      var updateJSON = function(data) {
        // $scope.logInfo = data;

        // translateToQuneeElements(data);
        editor.submitJSON(data);
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
        $window.$quneeNode = $node;
      };

      var bindListener = function() {
        $scope.getQuneeNodeInfo = getQuneeNodeInfo;
        $scope.getQuneeProcessInfo = getQuneeProcessInfo;
        $scope.getQuneeHistoryList = getQuneeHistoryList;
        $scope.getManagerProcessQuneeLogList = getManagerProcessQuneeLogList;
        $scope.getUserList = getUserList;
        $scope.createGroup = createGroup;
        $scope.translateToQuneeElements = translateToQuneeElements;
        $scope.initEditor = initEditor;
        $scope.updateJSON = updateJSON;
        $scope.getChartJSON = getChartJSON;
        $scope.initQuneeEvent = initQuneeEvent;
        $scope.toggleLog = toggleLog;
        $scope.getQuneeState = getQuneeState;
        $scope.getQuneeStateAndData = getQuneeStateAndData;
        $scope.getQuneeExecState = getQuneeExecState;
        $scope.submitUserConfirm = submitUserConfirm;
        $scope.activeUser = activeUser;
        $scope.submitEditorTakeOver = submitEditorTakeOver;
        $scope.submitProcessQuit = submitProcessQuit;
        $scope.socketPullData = socketPullData;

        // 监听qunee 所有事件
        $node.on('qunee.check', onQuneeCheck);
        $node.on('qunee.start', onQuneeStart);
        $node.on('qunee.pause', onQuneePause);
        $node.on('qunee.continue', onQuneeContinue);
        $node.on('qunee.quit', onQuneeQuit);
        // $node.on('qunee.onlyExecuteSelfNode', onQuneeOnlyExecuteSelfNode);
        // $node.on('qunee.fromExecuteSelfNode', onQuneeFromExecuteSelfNode);
        $node.on('qunee.skipSelfNode', onQuneeSkipSelfNode);
        $node.on('qunee.restartSelfNode', onQuneeRestartSelfNode);
        $node.on('qunee.manualNozzleNode', onQuneeManualNozzleNode);
        $node.on('qunee.stateChange', onStateChange);

        $node.on('qunee.info', onQuneeInfo);
        $node.on('qunee.history', onQuneeHistory);
      };

      var initPlugins = function() {

        window.historyProcess = true;

        $scope.logList = [];


        // 只监听跳转路由
        $rootScope.$on('$stateChangeStart', function() {
          console.log('跳转路由 清除执行id 下次进来');
          console.log('状态', $scope.quneeState);

          // 如果状态不为终止 执行成功 的话 则清除执行id
          if ($scope.quneeState === 'manualQuit' || $scope.quneeState === 'execSuccess') {
            ParseMapServ.removeItem(processId, 'quitState');
            ParseMapServ.removeItem(processId, 'process');
          };
        });

        // 保存当前流程id
        execId = $stateParams.id;
        processId = $stateParams.processId;
        // execId = ParseMapServ.getItem(processId, 'process') || 0;
        $scope.getManagerProcessQuneeLogList(execId);
        // 用户确认数据
        $scope.userConfirmModel = {
          errerMsg: '提示：用户确认超时2分钟。'
        };
        $scope.selectDefaultText = '请选择用户';
        $scope.stateConfig = {
          check: true,
          start: true,
          pause: true,
          quit: true
        };

        // 用户接管表单参数
        $scope.userEditorTakeOverModel = {
          check: 1,
          resultQuery: true,
          remark: ''
        };

        $scope.userEditorQuitModel = {
          remark: ''
        };

        // 初始化参数
        $scope.historyListState = false;
        $scope.nodeInfoState = false;
        $scope.logShowState = false;
        $scope.processInfoState = false;

        // 所有节点状态字典
        ManagerProcessQuneeServ.getManagerProcessQuneeStateMap()
        .then(function(result) {
          $scope.statusNodeMap = result;
          $window.statusNodeMap = result;
          getQuneeStateAndData();
        });

        // $scope.getUserList();
        // $scope.getQuneeHistoryList();
        $scope.getQuneeProcessInfo();
        $node.find('.htrd-c-button-group').eq(0).hide();
        $node.find('.qunee-history').hide();

        // 初始化socket链接
        // SocketServ.initSocket(processId);
        // SocketServ.onMessage(onPushNodeData);
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'config': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/quneeInfoHistory.html'
  };
}]);

// 下拉框带查询
angular.module('HTRD_AutoConsole.A').directive('selectFilter',['$state', '$timeout', function($state, $timeout, ManagerProcessTreeServ) {
  var link = function(s, e) {
    var $scope, $node;

    // 时时监听输入的内容 传递给控制器 发送请求
    var changeText = function() {
      console.log('changeText', $scope.text);
      $scope.callback && $scope.callback($scope.text);
    };

    var activeItem = function(item,$event) {
      $scope.selFlowTarget=$event.target;
      $scope.text = item.name;
      $scope.activeCallback && $scope.activeCallback(item);
      $scope.list = [];
    };

    // 焦点事件
    var changeFocus = function() {
      $timeout(function () {
        e.find("#listItem").stop(true,true).show();
      }, 300);

    };

    var changeBlur = function() {
      $timeout(function () {
        e.find("#listItem").stop(true,true).hide();
      }, 300)
    };

    var parseDOM = function() {
      $scope = s;
      $node = $(e[0]);
    };

    var bindListener = function() {
      $scope.changeText = changeText;
      $scope.activeItem = activeItem;
      $scope.changeBlur=changeBlur;
      $scope.changeFocus=changeFocus;
    };

    var initPlugins = function() {
      $scope.text = $scope.text || '';
      // 接收外面查询出来的数据
      $scope.$on('changeSelectFilterList', function(evt, data) {
        console.log('data.id', data.id);
        console.log('$scope.id', $scope.id);

        if (data.id === $scope.id) {
          $scope.list = data.data;
        };
      });
    };

    var init = function() {
      parseDOM();
      bindListener();
      initPlugins();
    };

    init();
  };
  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'callback': '=',
        'activeCallback': '=',
        'text': '=',
        'id': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/selectFilter.html'
  };
}]);

// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('selectMenu',[function() {
  var link = function(s, e) {
      var $scope, $node;

      var activeMenu = function(item) {
        console.log(11111)
        $scope.defaultText = item.title;
        $scope.menuCallback && $scope.menuCallback(item);
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.activeMenu = activeMenu;
      };

      var initPlugins = function() {
        // $node.find(".dropdown-menu").on('click', function (e) {
        //    e.stopPropagation();
        //  });
      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'list': '=',
        'defaultText': '=',
        'menuCallback': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/selectMenu.html'
  };
}]);

// 下拉框带tree
angular.module('HTRD_AutoConsole.A').directive('selectTree',['$state', 'ManagerProcessTreeServ',  function($state, ManagerProcessTreeServ) {
  var link = function(s, e) {
    var $scope, $node;
    var activeTree = function(item) {
      if (item.node && $scope.panelShow) {
        $scope.panelShow = false;
        //分类的id  item.node.id;
        switch ($scope.tag) {

          case 'classify':
            $scope.$emit("processEdit",{
              classify : item.node.id
            })
            break;

          case 'process':
            $scope.$emit("nodeInfoList",{
              quoteProcessSelect : item.node.id,
              tag: 'process'
            })
            break;

          default:
        };

        $scope.$apply(function() {
          $scope.defaultText = item.node.text;
          $scope.activeId = item.node.id;
        });
      };
    };

    // var initTreeData = function() {
    //   ManagerProcessTreeServ.getProcessTree()
    //   .then(function(result) {
    //     $scope.treeData = result.results.map($scope.setTreeData);
    //   });
    // };

    var togglePanel = function() {
      $scope.panelShow = !!!$scope.panelShow;
    };

    var parseDOM = function() {
      $scope = s;
      $node = $(e[0]);
    };

    var bindListener = function() {
      //$scope.initTreeData = initTreeData;
      $scope.togglePanel = togglePanel;
      //$scope.setTreeData = ManagerProcessTreeServ.setTreeData;
      $scope.activeTree = activeTree;
    };

    var initPlugins = function() {
      $scope.isInitLoad = true;
      //$scope.initTreeData();
    };

    var init = function() {
      parseDOM();
      bindListener();
      initPlugins();
    };

    init();
  };
  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'defaultText':'=',
        'treeData':'=',
        'tag':'='
      },
      'link': link,
      'templateUrl': 'view/directive/util/selectTree.html'
  };
}]);

// 滑动
angular.module('HTRD_AutoConsole.A').directive('slide',[function() {
	var link = function(s, e) {
		var $scope, $node;

    var switchActive = function() {
      $scope.active = !$scope.active;
      $scope.callback && $scope.callback($scope.active);
    };

		var parseDOM = function() {
			$scope = s;
			$node = $(e[0]);
		};

		var bindListener = function() {
      $scope.switchActive = switchActive;
		};

		var initPlugins = function() {
			$scope.active = $scope.defaultActive || false;
		};

		var init = function() {
			parseDOM();
			bindListener();
			initPlugins();
		};

		init();
	};
	return {
		'replace': true,
		'restrict' : 'AEC',
		'scope': {
			'defaultActive': '=',
			'callback': '='
		},
		'link': link,
		'templateUrl': 'view/directive/util/slide.html'
	};
}]);

// 选项卡
angular.module('HTRD_AutoConsole.A').directive('tab',[function() {
  var $scope, $node;
  var link = function(s, e) {

      var switchTab = function(item) {
        $scope.activeIndex = item.index;
        $scope.callback($scope.activeIndex);
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.switchTab = switchTab;
      };

      var initPlugins = function() {
        $scope.activeIndex = 1;
        $scope.tabList = [
          {
            index: 1,
            name: '基本属性'
          },

          {
            index: 2,
            name: '性能监控'
          }
          // ,
          //
          // {
          //   index: 3,
          //   name: '远程桌面'
          // },
        ];

        $scope.$watch('nodeInfo', function(n, o, scope) {
          $scope.activeIndex = 1;
          $scope.tabList[$scope.activeIndex - 1].active = true;
        });
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };
  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'nodeInfo': '=',
        'callback': '=',
				'type': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/tab.html'
  };
}]);

// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('timePicker',['$timeout',function($timeout) {
  var link = function(s, e) {
      var $scope, $node;

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };


      var bindListener = function() {

      };

      var initPlugins = function() {

        $node.find('#timepicker1').timepicker(
          {
            showMeridian: false,
            explicitMode: true,
            showSeconds: true,
            disableMousewheel: true
          }
        );

        var time_out = $("#timepicker1").val();
        $node.find('#timepicker1').on('changeTime.timepicker',function(e){
          $('#timeDisplay').text(e.time.value);
          time_out = e.time.value;

          $scope.$emit('timeOut',{
            timeOut: time_out
          });
        });

        $timeout(function(){
          $scope.$emit('timeOut',{
            timeOut: time_out
          })
        },1000)
      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {

      },
      'link': link,
      'templateUrl': 'view/directive/util/timePicker.html'
  };
}]);

// 时间
angular.module('HTRD_AutoConsole.A').directive('tree',[function() {
  var link = function(s, e) {
      var $scope, $node;
      var getStateClass = function(tabIndex, index) {
        var classArr = [
          ['glyphicon-pause', 'glyphicon-exclamation-sign', 'glyphicon-play'],
          ['glyphicon-ok-sign', 'glyphicon-user', 'glyphicon-off']
        ];
        return classArr[tabIndex][index];
      }
      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
      };

      var initPlugins = function() {
        $scope.tabs = ['执行中的流程', '已结束的流程'];
        $scope.tabs.active = '0';
        $scope.map = ['running', 'end'];
        $scope.getStateClass = getStateClass;
      };

      var init = function() {
        parseDOM();
        bindListener();
        initPlugins();
      };

      init();
  };
  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'treeData': '=',
        'processState': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/tree.html'
  };
}]);

// tree
angular.module('HTRD_AutoConsole.A').directive('treeItem', ['ManagerProcessTreeServ', function(ManagerProcessTreeServ) {
  var link = function(s, e) {
    var $scope, $node;
    var isInit = true;
    var initTree = function() {
      $scope.$watch('treeData', function() {
        $scope.treeData && $node.jstree({
          'core': {
            'check_callback': true,
            'data': $scope.treeData
          },
          'plugins': [
            'dnd', 'search', 'unique',
            'state', 'types', 'wholerow'
          ]
        });
      });

      // 默认选中根节点
      $node.on('loaded.jstree', function(e, data) {
        var inst = data.instance;
        var obj = inst.get_node(e.target.firstChild.firstChild.lastChild);
        inst.select_node(obj);
      });

      $node.on('changed.jstree', function (e, data) {
          //console.log(data.node.children);
          // if ($scope.selected[0] !== data.selected[0]) {
          //   $scope.selected = data.selected;
          //   $scope.callBack && $scope.callBack(data);
          // }

        if ($scope.selected[0] !== data.selected[0]) {
          $scope.selected = data.selected;

          if (!$scope.isInitLoad) {
            $scope.callBack && $scope.callBack(data);
          } else {
            $scope.isInitLoad = false;
          };
        };
      });

      // 监听展开文件夹事件
      $node.on('open_node.jstree', function(e, data) {
        // 通过未加载属性进行ajax展开tree
        if (data.node.li_attr.notload) {
          // 隐藏占位文件夹
          $('#' + data.node.children[0]).hide();
          // 加载tree
          ManagerProcessTreeServ.getProcessTreeById({
            // 'format': 'json',
            'id': data.node.id
          }).then(function(res) {
            // 删除占位文件夹
            $node.jstree().delete_node([data.node.children[0]]);

            // 移除未加载属性
            delete data.node.li_attr.notload;

            // 整理数据,后端的数据不符合tree生成
            var treeArr = res.results.children.map(ManagerProcessTreeServ.setTreeData);
            // // 由于create_node的限制,一次只能创建一个节点
            treeArr.forEach(function(item) {
              $node.jstree().create_node(data.node.id, item, 'last');
            });
          });
        }
      });
    };

    var parseDOM = function() {
      $scope = s;
      $node = $(e[0]);
    };

    var bindListener = function() {
      $scope.selected = '';
      $scope.initTree = initTree;
    };

    var initPlugins = function() {
      $scope.initTree();
    };

    var init = function() {
      parseDOM();
      bindListener();
      initPlugins();
    };

    init();
  };
  return {
    'replace': true,
    'restrict': 'AEC',
    'scope': {
      'treeData': '=',
      'callBack': '=',
      'isInitLoad': '='
    },
    'link': link,
    'templateUrl': 'view/directive/util/treeItem.html'
  };
}]);

// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('userSelect',[function() {
  var link = function(s, e) {
      var $scope, $node;

      var activeMenu = function(item) {
        $scope.defaultText = item.title;
        $scope.callBack && $scope.callBack(item);
      };

      var selectbox = function(item){
        var len = $scope.list.length;  //获取长度;
        var count = 0;
        $scope.defaultText = [];
        var ids = [];
        $scope.texts = [];
        item.checked = !!!item.checked;
        $scope.list.map(function(item){
          if(item.checked){
            $scope.texts.push(item.title);
            ids.push(item.id);
            count++;
          }
        });
        count == 0? $scope.defaultText = "请选择用户" : $scope.defaultText = $scope.texts.join(',');
        $scope.$emit('userList',{
          userIds: ids
        })
        console.log(ids);
        $scope.checkedAll = len === count;
      };


      var selectAll = function (item) {
        var ids = [];
        $scope.texts = [];
        var count = 0;
        $scope.checkedAll = !!!$scope.checkedAll;
          $scope.list.map(function(item){
            item.checked = $scope.checkedAll;
            if(item.checked){
              $scope.texts.push(item.title);
              ids.push(item.id);
              count++;
              //console.log(ids)
            }
          });
        console.log(ids);
        $scope.$emit('userList',{
          userIds: ids
        });
        count == 0? $scope.defaultText = "请选择用户" : $scope.defaultText = $scope.texts.join(',');
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.activeMenu = activeMenu;
        $scope.selectbox = selectbox;
        $scope.selectAll = selectAll;
      };

      var initPlugins = function() {
        $scope.texts = [];
        $scope.checkedAll = false;
        $node.find(".dropdown-menu").on('click', function (e) {
           e.stopPropagation();
         });

      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'list': '=',
        'defaultText': '=',
        'callBack': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/userSelect.html'
  };
}]);
